@babel/plugin-transform-object-rest-spread
This plugin is included in @babel/preset-env
, in ES2018
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"]
}
Via CLIโ
babel --plugins @babel/plugin-transform-object-rest-spread script.js
Via Node APIโ
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-object-rest-spread"],
});
Optionsโ
By default, this plugin will produce spec compliant code by using Babel's objectSpread
helper.
loose
โ
boolean
, defaults to false
.
Enabling this option will use Babel's extends
helper, which is basically the same as Object.assign
(see useBuiltIns
below to use it directly).
Consider migrating to the top level setSpreadProperties
assumption.
{
"assumptions": {
"setSpreadProperties": true
}
}
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.
For detailed information please check out Spread VS. Object.assign and Assigning VS. defining properties.
useBuiltIns
โ
boolean
, defaults to false
.
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);
You can read more about configuring plugin options here