Skip to main content

@babel/plugin-syntax-dynamic-import

info

这个插件包含在 @babel/preset-env 中,在 ES2020。

tip

如果你使用的是 @babel/core 7.8.0 或更高版本,你可以放心地从 Babel 配置中移除这个插件。

安装​

🌐 Installation

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

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}

通过 CLI​

🌐 Via CLI

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

通过 Node API​

🌐 Via Node API

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

使用 Webpack 和 @babel/preset-env​

🌐 Working with Webpack and @babel/preset-env

目前,@babel/preset-env 并不知道将 import() 与 Webpack 内部依赖 Promise 一起使用。像 Internet Explorer 这样的不支持内置 Promise 的环境,需要手动添加 promise 和 iterator 两个 polyfill。

🌐 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.

例如,使用 core-js@3:

🌐 For example, with core-js@3:

webpack.config.js
const config = {
entry: [
"core-js/modules/es.promise",
"core-js/modules/es.array.iterator",
path.resolve(__dirname, "src/main.js"),
],
// ...
};

or

src/main.js
import "core-js/modules/es.promise";
import "core-js/modules/es.array.iterator";

// ...

对于 core-js@2 也是一样,只是导入路径稍微不同:

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

webpack.config.js
const config = {
entry: [
"core-js/modules/es6.promise",
"core-js/modules/es6.array.iterator",
path.resolve(__dirname, "src/main.js"),
],
// ...
};

or

src/main.js
import "core-js/modules/es6.promise";
import "core-js/modules/es6.array.iterator";

// ...