为什么在Node中使用UMD时需要设置global.window?

时间:2019-06-25 01:24:46

标签: webpack babel umd

我有以下...

// 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?

(here is the code)

1 个答案:

答案 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'
},