【问题标题】:webpack 4 library target umd x is not a constructorwebpack 4 库目标 umd x 不是构造函数
【发布时间】:2019-05-10 00:29:22
【问题描述】:

我的 /src/index.js 中有这个 es6 类

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return `(${this.x}, ${this.y})`;
    }
}

export default Point;

这里是 webpack.config.js 文件

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    library: 'point',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

所以当我像这样包含在我的 index.html 文件中时:

<!DOCTYPE html>
<html>
<head>
    <title>Webpack</title>
</head>
<body>

    <!-- Scripts -->
    <script src="dist/bundle.js"></script>

    <script type="text/javascript">
        new point(1, 3).toString()
    </script>
</body>
</html>

所以我在控制台中有这个错误

"Uncaught TypeError: point is not a constructor"

这是 umd 脚本类型

为什么我在使用 webpack 编译时看到这个错误?

同样的场景使用汇总工作正常

有什么办法吗?

还有一件事我看到几乎每个开发人员都使用汇总用于 es6 包开发来编译脚本的“esm”、“umd”版本。

但我想使用 webpack 而不是汇总。

有什么指南吗?

谢谢

【问题讨论】:

    标签: javascript webpack webpack-4


    【解决方案1】:

    请在 Webpack 配置的output 部分添加libraryExport: 'default'

    这样的事情(对于你的情况),

    const path = require('path');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        library: 'point',
        libraryTarget: 'umd',
        umdNamedDefine: true,
        libraryExport: 'default',
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2018-01-20
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      相关资源
      最近更新 更多