跳至正文

@babel/plugin-proposal-import-defer

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

注意

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

示例

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

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

将转换为

output.js
"use strict";

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

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

安装

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

用法

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

通过 CLI

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

通过 Node API

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

参考