Reputation: 1534
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?
Upvotes: 7
Views: 6722
Reputation: 1534
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.
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"] }]]
}
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:
Upvotes: 13