Webpack 5 和 ESM

And*_*ock 11 javascript node.js webpack

我想我已经阅读了 SO 上的每个线程以及互联网上的每个相关页面,所有内容都有一些问题的变体

我想:

  • 使用 webpack 捆绑我的 Web 应用程序
  • 在我的源 js 中使用 ES 模块并将它们转译为更广泛的浏览器支持
  • 在我的 webpack 配置中使用 ES 模块

Node 14 据说支持 ESM,所以让我们使用它

设置1

"type": "module"在我的package.json

然后我的webpack.config.js看起来像:


import { somethingUseful } from './src/js/useful-things.js';

export default (env, argv) => {
    return {
        // webpack config here
    };
}
Run Code Online (Sandbox Code Playgroud)

运行> webpack(webpack-cli)我得到:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\git\Useroo\webpack.config.js
require() of ES modules is not supported.
require() of webpack.config.js from C:\nvm\v14.14.0\node_modules\webpack-cli\lib\groups\resolveConfig.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename webpack.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from package.json.

Run Code Online (Sandbox Code Playgroud)

好的,让我们按照错误消息的提示进行操作

设置 2a

"type": "module"如果我从我的中删除package.json我得到

webpack.config.js
import { somethingUseful } from './src/js/useful-things.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)

是的......所以让我们尝试其他建议的替代方案:

设置 2b

module.exports = async (env, argv) => {

    var somethingUseful = await import('./src/js/useful-things.js');

    return {
        // webpack config here
    };
}

Run Code Online (Sandbox Code Playgroud)

我遇到段错误。

/c/Program Files/nodejs/webpack: line 14: 14272 Segmentation fault "$basedir/node" "$basedir/node_modules/webpack/bin/webpack.js" "$@"

Tat*_*ton 16

webpack-cli现在支持 ES 模块。所需要的只是

  • 添加"type": "module"到你的 package.json

或者

  • 使用扩展名命名您的 webpack 配置mjswebpack.config.mjs


And*_*ock 3

在撰写本文时,webpack-cli 还不支持 ES6 模块,因此您基本上必须自己重新实现它。

其实没那么难,只是烦人而已。你需要这样的东西(为了简洁而简化):这里只是 RTFM https://webpack.js.org/api/node/

import webpack from 'webpack';
import webpackConfig from './webpack.config.js';


var config = await webpackConfig(mode);
var compiler = webpack(config);

compiler.watch()
Run Code Online (Sandbox Code Playgroud)