@babel/plugin-syntax-dynamic-import

NOTE: This plugin is included in @babel/preset-env, in ES2020

Installation

  1. npm install --save-dev @babel/plugin-syntax-dynamic-import

Usage

  1. {
  2. "plugins": ["@babel/plugin-syntax-dynamic-import"]
  3. }

Via CLI

  1. babel --plugins @babel/plugin-syntax-dynamic-import script.js

Via Node API

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-syntax-dynamic-import"],
  3. });

Working with Webpack and @babel/preset-env

Currently, @babel/preset-env is unaware that using import() with Webpack relies on Promise internally. Environments which do not have builtin support for Promise, like Internet Explorer, will require both the promise and iterator polyfills be added manually.

For example, with core-js@3:

  1. // webpack config
  2. const config = {
  3. entry: [
  4. "core-js/modules/es.promise",
  5. "core-js/modules/es.array.iterator",
  6. path.resolve(__dirname, "src/main.js"),
  7. ],
  8. // ...
  9. };

or

  1. // src/main.js
  2. import "core-js/modules/es.promise";
  3. import "core-js/modules/es.array.iterator";
  4. // ...

This is the same for core-js@2, except the imports paths are slightly different:

  1. // webpack config
  2. const config = {
  3. entry: [
  4. "core-js/modules/es6.promise",
  5. "core-js/modules/es6.array.iterator",
  6. path.resolve(__dirname, "src/main.js"),
  7. ],
  8. // ...
  9. };

or

  1. // src/main.js
  2. import "core-js/modules/es6.promise";
  3. import "core-js/modules/es6.array.iterator";
  4. // ...