跳至主内容

@babel/plugin-transform-dynamic-import

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

信息

此插件已包含在 @babel/preset-env 中,属于 ES2020 标准。

import() 表达式转换为非 ESM 模块格式。

何时(不)使用此插件

若你正在使用打包工具(如 Webpack、Rollup 或 Parcel),则不应使用此插件,而应让打包工具处理 import() 表达式。

在以下场景下应使用此插件:

此插件必须配合上述模块转换插件之一使用。

示例

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

将被转换为

output.js
Promise.resolve()
.then(() => _interopRequireWildcard(require("jquery")))
.then(($) => {});

安装

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

用法

通过配置文件(推荐)

babel.config.json
{
"plugins": [
"@babel/plugin-transform-dynamic-import",
"@babel/plugin-transform-modules-commonjs"
]
}

通过命令行

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

通过 Node API

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

参考