跳到主要内容

@babel/plugin-proposal-import-defer

Transforms import defer declarations to deferred require() calls.

警告

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

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

Via CLI

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

Via Node API

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

References