在前端使用 ES6 npm 模块(webpack)

using ES6 npm module (webpack) in the front end

本文关键字:模块 webpack npm ES6 前端      更新时间:2023-09-26

我正在通过webpack使用ES6语法(importsexports等)制作一个npm模块。

当我尝试在前端初始化导出类的实例以测试它时,它不起作用,我有一种感觉,这与CommonJS导出返回与ES6导出有关。

示例.js

export default class Example { ....

示例后网络包的东西.js

var Example = (function() ....

演示.js

var example = new Example();

演示.html

<script src="../example-after-webpack-stuff.js"></script>
<script src="demo.js"></script>

我收到以下内容:

错误:

未捕获的类型错误:示例不是函数

编辑

Webpack 配置:

module.exports = {
    entry: './src/example.js',
    output: {
        filename: "./dist/example.js",
        library: "Example",
        libraryTarget: "var"
    },
    module: {
        loaders: [
            {
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

从 babel 6 开始,export default class Example将被编译为 exports.default = Example 。而在 Babel 5 中,它将被编译为 exports = Example .因此,您的代码将使用 babel 5 运行而不会出错。

在 babel 6 中,你可以使用 CommonJS 方式module.exports

class Example {
  constructor() {
    ...
  }
}
module.exports = Example;

或者你可以使用 babel-plugin-add-module-exports 来改变 babel 6 的行为。

npm install babel-plugin-add-module-exports --save-dev

将其添加到 webpack.config.js:

loaders: [
  {
    exclude: /(node_modules|bower_components)/,
    loader: 'babel',
    query: {
      presets: ['es2015'],
      plugins: ['add-module-exports']
    }
  }
]