如何从browserify/babelify导出全局变量以在没有browserify的项目中使用? [英] How to export global variable from browserify/babelify to be used in project without browserify?
问题描述
场景:
我有2个项目,其设置完全不同:
I have 2 projects with quite different setup:
- 常规网站,具有简单gulp设置的旧代码
-
小型宠物项目.借助ES6类编写的JS滑块插件(与babel一起编译). JS gulp任务:
- 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/'));
});
我想实现什么?
我希望能够在此常规网站中使用browserify/babelify输出的文件(而无需设置整个browserify/babelify之类的东西).
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).
问题
当然,browserify/babelify做了一些神奇的事情,最后将变量包装到函数范围内,该函数范围隐藏了该变量/构造函数.因此,问题是导出可以在其他项目中使用的全局变量/构造函数的正确方法是什么?此时,我唯一想到的就是将函数附加到窗口对象上,例如:
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
还有其他想法吗?
推荐答案
设置standalone
选项:
当
opts.standalone
是非空字符串时,将使用该名称和 umd 创建一个独立模块. a>包装器.您可以在独立全局导出中使用名称空间,使用字符串名称中的.
作为分隔符,例如'A.B.C'
.全球出口将经过消毒和装箱的骆驼.
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.
这篇关于如何从browserify/babelify导出全局变量以在没有browserify的项目中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!