@babel/plugin-transform-dynamic-import
将 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
¥You are authoring a Node.js library in ESM but want to distribute it in CommonJS(CJS): Install this plugin and
@babel/plugin-transform-modules-commonjs
-
你使用 RequireJS 在浏览器中加载模块:安装此插件和
@babel/plugin-transform-modules-amd
¥You use RequireJS to load modules in the browser: Install this plugin and
@babel/plugin-transform-modules-amd
-
你使用 SystemJS 在浏览器中加载模块:安装此插件和
@babel/plugin-transform-modules-systemjs
¥You use SystemJS to load modules in the browser: Install this plugin and
@babel/plugin-transform-modules-systemjs
此插件必须与上述模块转换插件之一一起使用。
¥This plugin must be used with one of the module transform plugins mentioned above.
示例
¥Example
import("jquery").then($ => {});
将转变为
¥will be transformed to
- CommonJS
- AMD
- SystemJS
Promise.resolve()
.then(() => _interopRequireWildcard(require("jquery")))
.then(($) => {});
define(["require"], function (_require) {
new Promise((_resolve, _reject) =>
_require(
["jquery"],
(imported) => _resolve(_interopRequireWildcard(imported)),
_reject
)
).then(($) => {});
});
System.register([], function (_export, _context) {
"use strict";
return {
setters: [],
execute: function () {
_context.import("jquery").then(($) => {});
}
};
});
安装
¥Installation
- npm
- Yarn
- pnpm
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
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
{
"plugins": [
"@babel/plugin-transform-dynamic-import",
"@babel/plugin-transform-modules-commonjs"
]
}
通过 CLI
¥Via CLI
babel --plugins=@babel/plugin-transform-dynamic-import,@babel/plugin-transform-modules-amd script.js
通过 Node API
¥Via Node API
require("@babel/core").transformSync("code", {
plugins: [
"@babel/plugin-transform-dynamic-import",
"@babel/plugin-transform-modules-systemjs"
],
});
参考
¥References