Webpack 5 和 ESM [英] Webpack 5 and ESM

查看:62
本文介绍了Webpack 5 和 ESM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我已经阅读了 SO 上的每个主题以及互联网上的每个相关页面,每个问题都有一些变化

I think I've read every thread on SO and every related page on the internet on this, everything has some variation of a problem

我想要:

  • 使用 webpack 捆绑我的网络应用
  • 在我的源代码 js 中使用 ES 模块并将它们转译以获得更广泛的浏览器支持
  • 在我的 webpack 配置中使用 ES 模块

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

Node 14 allegedly supports ESM, so lets use that

设置 1

我的 package.json

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

then my webpack.config.js looks something like:


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

export default (env, argv) => {
    return {
        // webpack config here
    };
}

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

running > webpack (webpack-cli) I get:

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.

好的,让我们按照错误消息所说的去做

OK, so lets do what the error message says

设置 2a

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

If I remove "type": "module" from my package.json I get

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

SyntaxError: Cannot use import statement outside a module

对......所以让我们尝试另一个建议的替代方案:

right.... So lets try the other suggested alternative:

设置 2b

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

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

    return {
        // webpack config here
    };
}

我遇到了段错误.

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

推荐答案

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

At the time of writing, webpack-cli just doesn't support ES6 modules, so you basically have to re-implement it yourself.

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

It's not that hard really, just annoying. You need something like this (simplified for brevity): Just RTFM here 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()

这篇关于Webpack 5 和 ESM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆