Skip to main content

@babel/plugin-transform-spread

info

这个插件包含在 @babel/preset-env 中

示例​

🌐 Example

在

JavaScript
var a = ["a", "b", "c"];

var b = [...a, "foo"];

var c = foo(...a);

出

JavaScript
var a = ["a", "b", "c"];

var b = a.concat(["foo"]);

var c = foo.apply(void 0, a);

安装​

🌐 Installation

npm install --save-dev @babel/plugin-transform-spread

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

没有选项:

🌐 Without options:

babel.config.json
{
"plugins": ["@babel/plugin-transform-spread"]
}

有选项:

🌐 With options:

babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-spread",
{
"loose": true
}
]
]
}

通过 CLI​

🌐 Via CLI

Shell
babel --plugins @babel/plugin-transform-spread script.js

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-spread"],
});

选项​

🌐 Options

loose​

boolean,默认值为 false。

在宽松模式下,所有可迭代对象都被当作数组处理。

🌐 In loose mode, all iterables are assumed to be arrays.

caution

考虑迁移到顶层 iterableIsArray 假设。

babel.config.json
{
"assumptions": {
"iterableIsArray": true
}
}

在 iterableIsArray 假设下,Babel 在展开数组时会保留“空位”(例如,[ ...Array(2) ] 会生成 [ (hole), (hole) ])。将 iterableIsArray 设置为 false 可以避免这种行为。

🌐 Under the iterableIsArray assumption, Babel preserves "holes" when spreading an array (for example, [ ...Array(2) ] produces [ (hole), (hole) ]). Set iterableIsArray to false to avoid this behaviour.

tip

你可以在这里了解更多关于配置插件选项的内容

allowArrayLike​

boolean,默认值为 false

已添加于:v7.10.0

🌐 Added in: v7.10.0

此选项允许像数组一样传播类似数组的对象。

🌐 This option allows spreading array-like objects as if they were arrays.

caution

考虑迁移到顶层 arrayLikeIsIterable 假设。

babel.config.json
{
"assumptions": {
"arrayLikeIsIterable": true
}
}

类数组对象是一个具有 length 属性的对象:例如 { 0: "a", 1: "b", length: 2 }。注意,像真正的数组一样,类数组对象也可以有“空洞”:{ 1: "a", length: 3 } 等同于 [ (hole), "a", (hole) ]。

🌐 An array-like object is an object with a length property: for example, { 0: "a", 1: "b", length: 2 }. Note that, like real arrays, array-like objects can have "holes": { 1: "a", length: 3 } is equivalent to [ (hole), "a", (hole) ].

虽然把类数组对象当作数组来展开在规范上并不合规,但在支持 Symbol.iterator 的现代浏览器中,很多对象实际上是可迭代的。一些值得注意的例子是 DOM 集合,比如 document.querySelectorAll("img.big"),它们是这个选项的主要使用场景。

🌐 While it is not spec-compliant to spread array-like objects as if they were arrays, there are many objects that would be iterables in modern browsers with Symbol.iterator support. Some notable examples are the DOM collections, like document.querySelectorAll("img.big"), which are the main use case for this option.

请注意,即使禁用了这个选项,Babel 在旧引擎中仍然允许展开 arguments,因为它在 ECMAScript 规范中被定义为_可迭代_的。

🌐 Please note that Babel allows spreading arguments in old engines even if this option is disabled, because it's defined as iterable in the ECMAScript specification.

参考​

🌐 References