How can I preserve dynamic import statements with babel preset env?
Asked Answered
S

1

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?

Strapped answered 24/8, 2020 at 14:54 Comment(0)
S
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:

Strapped answered 24/8, 2020 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.