我有以下...
// src/index.mjs
class DoSomething{
constructor(){
console.log("Constructing");
}
doSomethingElse(){
console.log("Something else");
}
}
export { DoSomething };
// webpack config
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/index.mjs'),
output: {
filename: 'sce-umd.js',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.mjs$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
}
但是当我想在节点脚本中使用它时,我必须像这样首先声明窗口...
// WTF
global.window = global;
var DoSomething = require("../dist/sce-umd.js").DoSomething;
(function(){
var instance = new DoSomething();
instance.doSomethingElse();
})()
否则我会得到...
ReferenceError:未定义窗口
那么WTF?
答案 0 :(得分:1)
输出中缺少一些内容。
index.mjs
class DoSomething {
constructor() {
console.log("Constructing");
}
doSomethingElse() {
console.log("Something else");
}
}
export default DoSomething;
Webpack:
output: {
filename: './sce-umd.js',
library: 'DoSomething',
libraryTarget: 'umd',
libraryExport: 'default',
umdNamedDefine: true,
globalObject: 'this'
},