How to export global variable from browserify/babelify to be used in project without browserify?

空扰寡人 提交于 2019-12-13 02:27:37

问题


Scenario:

I have 2 projects with quite different setup:

  1. Regular website, legacy code with simple gulp setup
  2. 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.standalone is 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!