Peter
Peter

Reputation: 2394

Dynamically import webpack in Node.js

I´m trying to dynamically import webpack in Node.js

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

However in my terminal I see the following error:

    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.

I have @babel/plugin-syntax-dynamic-import installed and in my .babelrc

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

I even tried to add it to the webpack conf file under the rule for .js with loader "babel-loader".

I´m trying to avoid CmJS

const webpack = require('webpack');

In any case I receive the same error and I cannot find a solution. Did anyone go through this? Thanks

Upvotes: 1

Views: 2115

Answers (1)

afcfzf
afcfzf

Reputation: 29

add plugins: ["dynamic-import-webpack"] to .babelrc

and also install plug $npm i babel-plugin-dynamic-import-webpack --D

Upvotes: 1

Related Questions