【问题标题】:Why do I need to set global.window when using UMD in Node?为什么在 Node 中使用 UMD 时需要设置 global.window?
【发布时间】:2019-06-25 01:24:46
【问题描述】:

我有以下...

// 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: 未定义窗口

这么说吧?

(here is the code)

【问题讨论】:

    标签: webpack babeljs umd


    【解决方案1】:

    输出中缺少一些内容。

    index.mjs

    class DoSomething {
      constructor() {
        console.log("Constructing");
      }
      doSomethingElse() {
        console.log("Something else");
      }
    }
    
    export default DoSomething;
    

    网页包:

    output: {
      filename: './sce-umd.js',
      library: 'DoSomething',
      libraryTarget: 'umd',
      libraryExport: 'default',
      umdNamedDefine: true,
      globalObject: 'this'
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多