@babel/plugin-transform-dynamic-import
info
这个插件包含在 @babel/preset-env 中,在 ES2020。
将 import() 表达式转换为非 ESM 模块格式。
🌐 Transforms import() expressions to non-ESM module formats.
何时(不)使用此插件
🌐 When (not) to use this plugin
如果你正在使用打包工具,比如 Webpack、Rollup 或 Parcel,你不应该使用这个插件,而应该让你的打包工具处理 import() 表达式。
🌐 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:
- 你正在用 ESM 编写一个 Node.js 库,但想要以 CommonJS(CJS)分发:安装这个插件然后
@babel/plugin-transform-modules-commonjs - 你在浏览器中使用 RequireJS 来加载模块:安装这个插件和
@babel/plugin-transform-modules-amd - 你可以使用 SystemJS 在浏览器中加载模块:安装这个插件并
@babel/plugin-transform-modules-systemjs
此插件必须与上述模块转换插件之一一起使用。
🌐 This plugin must be used with one of the module transform plugins mentioned above.
示例
🌐 Example
input.js
import("jquery").then($ => {});
将转变为
🌐 will be transformed to
- 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(($) => {});
}
};
});
安装
🌐 Installation
- 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
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
babel.config.json
{
"plugins": [
"@babel/plugin-transform-dynamic-import",
"@babel/plugin-transform-modules-commonjs"
]
}
通过 CLI
🌐 Via CLI
Shell
babel --plugins=@babel/plugin-transform-dynamic-import,@babel/plugin-transform-modules-amd script.js
通过 Node API
🌐 Via Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: [
"@babel/plugin-transform-dynamic-import",
"@babel/plugin-transform-modules-systemjs"
],
});
参考
🌐 References