[英]How to expose an es6 module globally
我需要編寫一個可在全局窗口上使用的模塊。
我正在使用es6來創建模塊,我定義的每個類都有自己的文件。
我正在使用webpack來babelify並捆綁這些類。
我的模塊的入口點也是包含要公開的全局的文件。
我已經嘗試過各種方法來實現這個可能性,包括:
我試過的代碼示例:
我想得到:window.MyMod
// mymod.js
export class MyMod {
constructor(aaa) {
this.aaa = aaa;
}
toString() {
return this.aaa;
}
}
// webpack.config
var entries = [
'./src/mymod.js'
];
module.exports = {
...,
module: {
loaders: [
{
test: require.resolve('./src/mymod.js'),
loader: 'expose?MyMod'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
這只會讓我在包含MyMod作為構造函數的窗口上找到一個MyMod對象。
任何幫助將不勝感激。
這與使用Webpack和Babel導出類不起作用基本相同,除了您有一個命名導出而不是默認導出。 你的輸入文件應該是
import {MyMod} from './mymod';
module.exports = MyMod;
要么
module.exports = require('./mymod').MyMod;
如果您不想執行任何這些操作並將'./src/mymod.js'
保留為條目文件,請在該文件中使用CommonJS導出而不是ES6導出:
// mymod.js
exports.MyMod = class MyMod {
constructor(aaa) {
this.aaa = aaa;
}
toString() {
return this.aaa;
}
}
您應該將export default class Foo
與libraryTarget
配置中的library
和libraryTarget
設置組合在一起。 就像是:
// src/Foo.js
export default class Foo { ... }
// webpack.config.json
{
"output": {
"library": "Foo",
"libraryTarget": "var"
}
}
一旦加載了包,您應該能夠將庫用作window.Foo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.