简体   繁体   English

webpackConfig 上的 ESM 导入

[英]ESM import on webpackConfig

I'm building a webpack app and I'm interested in use ESM through the entire app, meaning that build the webpack.config file with ESM imports.我正在构建一个 webpack 应用程序,我有兴趣在整个应用程序中使用 ESM,这意味着使用 ESM 导入构建 webpack.config 文件。

I now this is possible using Babel, but this was before npm added the "type": "module" supporting now ESM imports without babel... I already tried it with Express and it worked but with Webpack I get this:我现在可以使用 Babel,但这是在 npm 添加"type": "module"之前支持现在没有 babel 的 ESM 导入......我已经用 Express 尝试过它并且它可以工作,但是使用 Webpack 我明白了:

> ...proyectDirectory/node_modules/webpack-cli/bin/cli.js:93

> require() of ES modules is not supported.

So I was wondering if there is a version of webpack-cli that use import instead of require所以我想知道是否有使用import而不是require的 webpack-cli 版本

Webpack CLI is expecting a commonJS file. Webpack CLI 需要一个 commonJS 文件。 There is experimental support for .mjs file that can be enabled using the experiments.mjs flag but it seems there are a number of issues around that.可以使用 Experiments.mjs 标志启用对.mjs文件的experiments.mjs性支持,但似乎存在许多问题。 So you can use webpack by using either no config or using a .cjs config as:因此,您可以通过使用无配置或使用.cjs配置来使用 webpack:

 ./node_modules/.bin/webpack-cli --config webpack.config.cjs

Also keep in mind that things like Jest do not work with esm (as of this date) so you'd need to use another test suite if no babel/esm was desired.还要记住,像 Jest 这样的东西不适用于 esm(截至目前),因此如果不需要 babel/esm,您需要使用另一个测试套件。

Update to at least webpack-cli 4.5.0.至少更新到 webpack-cli 4.5.0。 Support for native ESM configuration files has just been added: https://github.com/webpack/webpack-cli/releases/tag/webpack-cli%404.5.0刚刚添加了对原生 ESM 配置文件的支持: https://github.com/webpack/webpack-cli/releases/tag/webpack-cli%404.5.0

This means that if you're using webpack.config.js in a directory with {"type": "module"} in its package.json, it will work.这意味着,如果您在其 package.json 中包含{"type": "module"}的目录中使用webpack.config.js ,它将起作用。

It will also work if you simply name your file webpack.config.mjs如果您只是将文件命名为webpack.config.mjs ,它也将起作用

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

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