简体   繁体   English

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

[英]webpack 4 library target umd x is not a constructor

i have this es6 class in my /src/index.js 我的/src/index.js中有这个es6类

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

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

export default Point;

here is the webpack.config.js file 这是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'
  }
};

so when i include in my index.html file like this: 所以当我在我的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>

so i have this error in console 所以我在控制台中有此错误

"Uncaught TypeError: point is not a constructor" “未捕获的TypeError:点不是构造函数”

this is umd script type 这是umd脚本类型

why i'm seeing this error while compile with webpack? 为什么在用webpack编译时看到此错误?

same scenario working fine with rollup 相同的情况下汇总工作正常

is there any solution? 有什么解决办法吗?

and one more thing i saw almost every developer use rollup for es6 package development to compile "esm", "umd" versions of the script. 另外,我看到几乎所有开发人员都使用汇总来进行es6软件包开发,以编译脚本的“ esm”,“ umd”版本。

but i want to use webpack instead of rollup. 但我想使用webpack而不是汇总。

any guide? 有指导吗?

thanks 谢谢

Please add libraryExport: 'default' , in output section of Webpack configuration. 请在Webpack配置的output部分中添加libraryExport: 'default'

something like this (for your case), 这样的事情(针对您的情况),

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM