@babel/plugin-transform-dynamic-import

dynamic-import - 图1info

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

Transforms import() expressions to non-ESM module formats.

When (not) to use this plugin

If you are using a bundler, such as Webpack, Rollup or Parcel, you should not use this plugin and let your bundler handle import() expressions.

You should use this plugin if:

This plugin must be used with one of the module transform plugins mentioned above.

Example

input.js

  1. import("jquery").then($ => {});

will be transformed to

  • CommonJS
  • AMD
  • SystemJS

output.js

  1. Promise.resolve()
  2. .then(() => _interopRequireWildcard(require("jquery")))
  3. .then(($) => {});

output.js

  1. define(["require"], function (_require) {
  2. new Promise((_resolve, _reject) =>
  3. _require(
  4. ["jquery"],
  5. (imported) => _resolve(_interopRequireWildcard(imported)),
  6. _reject
  7. )
  8. ).then(($) => {});
  9. });

output.js

  1. System.register([], function (_export, _context) {
  2. "use strict";
  3. return {
  4. setters: [],
  5. execute: function () {
  6. _context.import("jquery").then(($) => {});
  7. }
  8. };
  9. });

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-dynamic-import
  1. yarn add --dev @babel/plugin-transform-dynamic-import
  1. pnpm add --save-dev @babel/plugin-transform-dynamic-import

Usage

babel.config.json

  1. {
  2. "plugins": [
  3. "@babel/plugin-transform-dynamic-import",
  4. "@babel/plugin-transform-modules-commonjs"
  5. ]
  6. }

Via CLI

Shell

  1. babel --plugins=@babel/plugin-transform-dynamic-import,@babel/plugin-transform-modules-amd script.js

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: [
  3. "@babel/plugin-transform-dynamic-import",
  4. "@babel/plugin-transform-modules-systemjs"
  5. ],
  6. });

References