如何使用 babel 和 webpack 将导出的函数公开到全局范围
How expose a exported function into global scope with babel and webpack
如何使用 webpack 和 babel 编译我的代码,以便导出的函数在全局范围内可用。
例如:
export function test(){console.log('test')}
应该在 window.test()
下可用。
当我 运行 babel -d
我得到了我期望的结果:
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.test = test;
function test() {
console.log('test');
}
但是 webpack 输出看起来像这样:
!function(e) {
function t(r) {
if (o[r])return o[r].exports;
var n = o[r] = {exports: {}, id: r, loaded: !1};
return e[r].call(n.exports, n, n.exports, t), n.loaded = !0, n.exports
}
var o = {};
return t.m = e, t.c = o, t.p = "", t(0)
}([function(e, t) {
"use strict";
function o() {
console.log("test")
}
Object.defineProperty(t, "__esModule", {value: !0}), t.test = o
}]);
结束 test
函数在全局范围内不可用。
查看:
https://github.com/webpack/docs/wiki/library-and-externals#examples
通过将 library 输出 属性 设置为您想要包装全局变量的任何名称,您可以调用:YourLibrary.test();
module.exports = {
entry: ['./_js/script.js'],
output: {
library: 'YourLibrary',
path: __dirname,
filename: './build/script.js'
}
您可以轻松地在全局 window
对象上设置 属性。这会将您的对象暴露给全局范围。
function test() {
console.log('test');
}
window.test = test;
如果您正在开发一段不代表库的代码,而只是在全局范围内运行的一些操作或功能,我更喜欢这种方法而不是设置库输出 属性 中提到的接受的答案。
如何使用 webpack 和 babel 编译我的代码,以便导出的函数在全局范围内可用。
例如:
export function test(){console.log('test')}
应该在 window.test()
下可用。
当我 运行 babel -d
我得到了我期望的结果:
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.test = test;
function test() {
console.log('test');
}
但是 webpack 输出看起来像这样:
!function(e) {
function t(r) {
if (o[r])return o[r].exports;
var n = o[r] = {exports: {}, id: r, loaded: !1};
return e[r].call(n.exports, n, n.exports, t), n.loaded = !0, n.exports
}
var o = {};
return t.m = e, t.c = o, t.p = "", t(0)
}([function(e, t) {
"use strict";
function o() {
console.log("test")
}
Object.defineProperty(t, "__esModule", {value: !0}), t.test = o
}]);
结束 test
函数在全局范围内不可用。
查看: https://github.com/webpack/docs/wiki/library-and-externals#examples
通过将 library 输出 属性 设置为您想要包装全局变量的任何名称,您可以调用:YourLibrary.test();
module.exports = {
entry: ['./_js/script.js'],
output: {
library: 'YourLibrary',
path: __dirname,
filename: './build/script.js'
}
您可以轻松地在全局 window
对象上设置 属性。这会将您的对象暴露给全局范围。
function test() {
console.log('test');
}
window.test = test;
如果您正在开发一段不代表库的代码,而只是在全局范围内运行的一些操作或功能,我更喜欢这种方法而不是设置库输出 属性 中提到的接受的答案。