@babel/plugin-proposal-dynamic-import
資訊
此外掛程式包含在 @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
npm install --save-dev @babel/plugin-proposal-dynamic-import
yarn add --dev @babel/plugin-proposal-dynamic-import
pnpm add --save-dev @babel/plugin-proposal-dynamic-import
用法
使用設定檔(建議)
babel.config.json
{
"plugins": [
"@babel/plugin-proposal-dynamic-import",
"@babel/plugin-transform-modules-commonjs"
]
}
透過 CLI
Shell
babel --plugins=@babel/plugin-proposal-dynamic-import,@babel/plugin-transform-modules-amd script.js
透過 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: [
"@babel/plugin-proposal-dynamic-import",
"@babel/plugin-transform-modules-systemjs"
],
});