Skip to main content

@babel/plugin-proposal-import-defer

import defer 声明转换为延迟的 require() 调用。

¥Transforms import defer declarations to deferred require() calls.

提醒

该插件只能在将模块编译为 CommonJS 时使用。

¥This plugin can only be used when also compiling modules to CommonJS.

示例

¥Example

input.js
import defer * as lib from "lib";

later(() => {
console.log(lib.value);
});

将转变为

¥will be transformed to

output.js
"use strict";

function lib(data) {
lib = () => data;
return data = _interopRequireWildcard(require("lib"));
}

later(() => {
console.log(lib().value);
});

安装

¥Installation

npm install --save-dev @babel/plugin-proposal-import-defer

用法

¥Usage

¥With a configuration file (Recommended)

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

通过 CLI

¥Via CLI

Shell
babel --plugins=@babel/plugin-proposal-import-defer,@babel/plugin-transform-modules-commonjs script.js

通过 Node API

¥Via Node API

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

参考

¥References