7

I am creating shared modules that contain dynamic imports for code splitting.

I have code like:

import('./moduleA').then(/* do stuff */)

However babel compiles this to a deferred require which stops Webpack from code splitting.

The transformed result looks like:

Promise.resolve().then(() => require('./moduleA')).then(/* do stuff */)

My .babelrc.json is simple and only contains:

{
  "presets": ["@babel/preset-env"]
}

How can I preserve the dynamic imports in my babel transformed code?

1 Answer 1

13

This is happening because @babel/preset-env by default includes a plugin, @babel/plugin-proposal-dynamic-import, that transforms dynamic imports.

There are two ways to stop this.

Option One (recommended)

You can exclude the plugin @babel/plugin-proposal-dynamic-import so the import() statements stay untouched. Update your preset options with the following:

{
  "presets": [["@babel/preset-env", { "exclude": ["proposal-dynamic-import"] }]]
}

Option Two

In the preset options add "modules": false, however this will also preserve ES module import/export statements.

{
  "presets": [["@babel/preset-env", { "modules": false }]]
}

This is described in depth in these GitHub Issues:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.