问题
Scenario:
I have 2 projects with quite different setup:
- Regular website, legacy code with simple gulp setup
Small pet project. JS slider plugin written with help of ES6 classes (transpiled with babel). JS gulp task:
gulp.task('js', function() { return gulp.src('src/scripts/*.js') .pipe($.plumber()) .pipe(through2.obj(function (file, enc, next) { browserify(file.path, { debug: true }) .transform(require('babelify')) .transform(require('debowerify')) .bundle(function (err, res) { if (err) { return next(err); } file.contents = res; next(null, file); }); })) .on('error', function (error) { console.log(error.stack); this.emit('end') }) .pipe( $.rename('alder.js')) .pipe( gulp.dest('dist/scripts/'));});
What I want to achieve?
I'd like to be able to use the file outputed by browserify/babelify in this regular website (without setting up the whole browserify/babelify stuff).
The question
Of course browserify / babelify does some magic stuff and finally wraps the variable into function scope what hides this variable/constructor function. So the question is what is the correct way to export global variable / constructor function that can be used in other projects? At this point the only thing that comes to my mind is to attach my function to the window object like:
class Alder { // constructor and then methods }
export default Alder;
window['Alder'] = Alder
Any other ideas?
回答1:
Set the standalone option:
When
opts.standaloneis a non-empty string, a standalone module is created with that name and a umd wrapper. You can use namespaces in the standalone global export using a.in the string name as a separator, for example'A.B.C'. The global export will be sanitized and camel cased.
来源:https://stackoverflow.com/questions/39581803/how-to-export-global-variable-from-browserify-babelify-to-be-used-in-project-wit