1

我正在尝试在 Node.js 中动态导入 webpack

if (condition) {
  import('webpack').then(webpack => webpack);
}

但是在我的终端中,我看到以下错误:

    C:\Users\myUser\react\node_modules\@babel\core\lib\transformation\normalize-file.js:209
        throw err;
        ^

    SyntaxError: C:\Users\myUser\react\server\index.js: Support for the experimental syntax 'dynamicImport' isn't currently enabled (23:3):


      19 |
      20 | if (condition) {
    > 21 |   import('webpack').then(webpack => webpack);
         |   ^
      22 |

Add @babel/plugin-syntax-dynamic-import (https://git.io/vb4Sv) to the 'plugins' section of your Babel config to enable parsing.

我在我的 .babelrc 中安装了 @babel/plugin-syntax-dynamic-import

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-proposal-class-properties"
  ]
}

我什至尝试将其添加到带有加载器“babel-loader”的 .js 规则下的 webpack conf 文件中。

我试图避免 CmJS

const webpack = require('webpack');

无论如何,我都会收到相同的错误,但找不到解决方案。有没有人经历过这个?谢谢

4

1 回答 1

1

添加plugins: ["dynamic-import-webpack"]到 .babelrc

并安装插头$npm i babel-plugin-dynamic-import-webpack --D

于 2019-04-26T06:48:00.657 回答