@babel/plugin-transform-dynamic-import
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
此插件已包含在 @babel/preset-env 中,属于 ES2020 标准。
将 import() 表达式转换为非 ESM 模块格式。
何时(不)使用此插件
若你正在使用打包工具(如 Webpack、Rollup 或 Parcel),则不应使用此插件,而应让打包工具处理 import() 表达式。
在以下场景下应使用此插件:
-
使用 ESM 编写 Node.js 库但需以 CommonJS(CJS) 格式分发时:安装此插件及
@babel/plugin-transform-modules-commonjs -
在浏览器中使用 RequireJS 加载模块时:安装此插件及
@babel/plugin-transform-modules-amd -
在浏览器中使用 SystemJS 加载模块时:安装此插件及
@babel/plugin-transform-modules-systemjs
此插件必须配合上述模块转换插件之一使用。
示例
input.js
import("jquery").then($ => {});
将被转换为
- CommonJS
- AMD
- SystemJS
output.js
Promise.resolve()
.then(() => _interopRequireWildcard(require("jquery")))
.then(($) => {});
output.js
define(["require"], function (_require) {
new Promise((_resolve, _reject) =>
_require(
["jquery"],
(imported) => _resolve(_interopRequireWildcard(imported)),
_reject
)
).then(($) => {});
});
output.js
System.register([], function (_export, _context) {
"use strict";
return {
setters: [],
execute: function () {
_context.import("jquery").then(($) => {});
}
};
});
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-dynamic-import
yarn add --dev @babel/plugin-transform-dynamic-import
pnpm add --save-dev @babel/plugin-transform-dynamic-import
bun add --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"
],
});