Skip to main content

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

info

这个插件包含在 @babel/preset-env 中,在 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。

启用此选项将使用 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).

caution

考虑迁移到顶层 setSpreadProperties 假设。

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

请记住,即使它们几乎相等,spread 和 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.

想了解详细信息,请查看 Spread 与 Object.assign 和 赋值与定义属性。

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

useBuiltIns​

boolean,默认值为 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 }]
]
}

在

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

出

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

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

参考​

🌐 References