@babel/plugin-transform-object-rest-spread
示例
¥Example
剩余属性
¥Rest Properties
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
let n = { x, y, ...z };
console.log(n); // { x: 1, y: 2, a: 3, b: 4 }
安装
¥Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-object-rest-spread
yarn add --dev @babel/plugin-transform-object-rest-spread
pnpm add --save-dev @babel/plugin-transform-object-rest-spread
bun add --dev @babel/plugin-transform-object-rest-spread
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-object-rest-spread"]
}
通过 CLI
¥Via CLI
babel --plugins @babel/plugin-transform-object-rest-spread script.js
通过 Node API
¥Via Node API
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.
{
"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
{
"assumptions": {
"setSpreadProperties": true
},
"plugins": [
["@babel/plugin-transform-object-rest-spread", { "useBuiltIns": true }]
]
}
输入
¥In
z = { x, ...y };
输出
¥Out
z = Object.assign({ x }, y);
参考
¥References