@babel/plugin-transform-spread
此插件包含在 @babel/preset-env
中
¥This plugin is included in @babel/preset-env
示例
¥Example
输入
¥In
var a = ["a", "b", "c"];
var b = [...a, "foo"];
var c = foo(...a);
输出
¥Out
var a = ["a", "b", "c"];
var b = a.concat(["foo"]);
var c = foo.apply(void 0, a);
安装
¥Installation
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-spread
yarn add --dev @babel/plugin-transform-spread
pnpm add --save-dev @babel/plugin-transform-spread
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
没有选项:
¥Without options:
{
"plugins": ["@babel/plugin-transform-spread"]
}
有选项:
¥With options:
{
"plugins": [
[
"@babel/plugin-transform-spread",
{
"loose": true
}
]
]
}
通过 CLI
¥Via CLI
babel --plugins @babel/plugin-transform-spread script.js
通过 Node API
¥Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-spread"],
});
选项
¥Options
loose
boolean
,默认为 false
。
¥boolean
, defaults to false
.
在松散模式下,所有可迭代对象都被假定为数组。
¥In loose mode, all iterables are assumed to be arrays.
考虑迁移到顶层 iterableIsArray
假设。
¥Consider migrating to the top level iterableIsArray
assumption.
{
"assumptions": {
"iterableIsArray": true
}
}
在 iterableIsArray
假设下,Babel 在扩展数组时保留 "holes"(例如,[ ...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.
allowArrayLike
boolean
,默认为 false
¥boolean
, defaults to false
添加于:v7.10.0
¥Added in: v7.10.0
此选项允许像数组一样传播类似数组的对象。
¥This option allows spreading array-like objects as if they were arrays.
考虑迁移到顶层 arrayLikeIsIterable
假设。
¥Consider migrating to the top level arrayLikeIsIterable
assumption.
{
"assumptions": {
"arrayLikeIsIterable": true
}
}
类数组对象是具有 length
属性的对象:例如,{ 0: "a", 1: "b", length: 2 }
。请注意,与真正的数组一样,类数组对象可以具有 "holes":{ 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