Skip to main content

@babel/plugin-transform-object-rest-spread

信息

此插件包含在 @babel/preset-env 中,在 ES2018

¥This plugin is included in @babel/preset-env, in ES2018

示例

¥Example

剩余属性

¥Rest Properties

JavaScript
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }

传播属性

¥Spread Properties

JavaScript
let n = { x, y, ...z };
console.log(n); // { x: 1, y: 2, a: 3, b: 4 }

安装

¥Installation

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

用法

¥Usage

¥With a configuration file (Recommended)

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

通过 CLI

¥Via CLI

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

通过 Node API

¥Via Node API

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

选项

¥Options

默认情况下,此插件将使用 Babel 的 objectSpread 助手生成符合规范的代码。

¥By default, this plugin will produce spec compliant code by using Babel's objectSpread helper.

loose

boolean,默认为 false

¥boolean, defaults to false.

启用该选项将使用 Babel 的 extends 助手,它与 Object.assign 基本相同(请参阅下面的 useBuiltIns 直接使用它)。

¥Enabling this option will use Babel's extends helper, which is basically the same as Object.assign (see useBuiltIns below to use it directly).

提醒

考虑迁移到顶层 setSpreadProperties 假设。

¥Consider migrating to the top level setSpreadProperties assumption.

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

请记住,即使它们几乎相同,点差和 Object.assign 之间也存在重要区别:spread 定义新属性,而 Object.assign() 设置它们,因此在某些情况下使用此模式可能会产生意外结果。

¥Please keep in mind that even if they're almost equivalent, there's an important difference between spread and Object.assign: spread defines new properties, while Object.assign() sets them, so using this mode might produce unexpected results in some cases.

有关详细信息,请查看 传播 VS。Object.assign分配 VS。定义属性

¥For detailed information please check out Spread VS. Object.assign and Assigning VS. defining properties.

useBuiltIns

boolean,默认为 false

¥boolean, defaults to false.

启用此选项将直接使用 Object.assign 而不是 Babel 的 extends 助手。

¥Enabling this option will use Object.assign directly instead of the Babel's extends helper.

示例

¥Example

.babelrc

JSON
{
"assumptions": {
"setSpreadProperties": true
},
"plugins": [
["@babel/plugin-transform-object-rest-spread", { "useBuiltIns": true }]
]
}

输入

¥In

JavaScript
z = { x, ...y };

输出

¥Out

JavaScript
z = Object.assign({ x }, y);
提示

你可以阅读有关配置插件选项 此处 的更多信息

¥You can read more about configuring plugin options here

参考

¥References