我最近使用模块导入/导出将一堆旧的 JS 重写为 ES2015。我正在使用 Rollup 和 Babel 将其转译回来。
这些库已集成到我无法控制的许多其他站点中,因此我需要谨慎对待代码,以确保我不会污染全局,不会引发错误等。
gulpfile.js
var rollupBabel = rollupPluginBabel({
babelrc: false,
presets: [
"babel-preset-es2015-rollup"
]
});
merged.add(rollup({
entry: './js/bnr.js',
format: "es",
plugins: [
rollupBabel
]
})
.pipe(source('bnr.js'))
.pipe(gulp.dest('./compiled/js/')));
bnr.js
import * as helpers from "../lib/helpers";
import moment from "../../node_modules/moment/src/moment";
class Connect {
constructor(window, document) {
this.init();
}
init()
{
// Stuff happens here
}
}
输出
// Helpers and what not here
var hookCallback;
function hooks() {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback(callback) {
hookCallback = callback;
}
function isArray(input) {
return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
}
// The rest of moment.js
如您所见,所有与 moment.js 相关的代码都在没有闭包/包装器的情况下输出,以使其远离全局。结果,我在使用网站时遇到了各种错误。
如何在不污染全局命名空间的情况下导入 moment.js 或重新配置 gulp 任务以导入 moment?
谢谢
最佳答案
正如@Bergi 所建议的那样,格式是问题所在,切换到 iife
将整个内容包装在一个闭包中以解决问题。
关于javascript - ES2015 模块导入污染全局命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301261/