webpack 4库目标umd x不是构造函数

时间:2018-12-08 13:40:46

标签: javascript webpack webpack-4

我的/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>

所以我在控制台中遇到此错误

  

“未捕获的TypeError:点不是构造函数”

这是umd脚本类型

为什么在用webpack编译时看到此错误?

相同的情况下可以很好地进行汇总

有什么解决办法吗?

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

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

任何指南?

谢谢

1 个答案:

答案 0 :(得分:0)

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

类似的情况(针对您的情况)

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'
  }
};