What is babel-plugin-transform-object-rest-spread?
The babel-plugin-transform-object-rest-spread package allows developers to use the object rest and spread properties syntax in their JavaScript code. This syntax is part of the ECMAScript 2018 (ES9) specification and enables more concise and readable code when copying properties from one object to another or collecting the remaining properties of an object after certain properties have been extracted.
What are babel-plugin-transform-object-rest-spread's main functionalities?
Object Spread
Allows an object's own enumerable properties to be copied into a new object. This is useful for creating a new object with the same properties as an existing object or for combining multiple objects.
{...source}
Object Rest
Enables extracting properties from objects and binding the remaining properties to a new object. This is useful for object destructuring, where you want to separate certain properties from the rest.
{a, b, ...rest}
Other packages similar to babel-plugin-transform-object-rest-spread
@babel/plugin-proposal-object-rest-spread
This is the official Babel plugin for transforming object rest and spread syntax. It is similar to babel-plugin-transform-object-rest-spread but is maintained as part of the Babel 7 release. It is the recommended package to use for Babel 7 users.
babel-preset-stage-3
This preset includes various Babel plugins for JavaScript features that are in stage 3 of the TC39 process, including object rest and spread properties. It is broader in scope compared to babel-plugin-transform-object-rest-spread, which focuses only on object rest and spread properties.
babel-plugin-transform-object-rest-spread
This plugin allows Babel to transform rest properties for object destructuring assignment and spread properties for object literals.
Example
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x);
console.log(y);
console.log(z);
let n = { x, y, ...z };
console.log(n);
Try in REPL
Installation
npm install --save-dev babel-plugin-transform-object-rest-spread
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["transform-object-rest-spread"]
}
Options
This plugin will use babel's extends
helper, which will polyfill Object.assign
by default.
useBuiltIns
- Do not use Babel's helper's and just transform to use the built-in method (Disabled by default).
{
"plugins": [
["transform-object-rest-spread", { "useBuiltIns": true }]
]
}
z = { x, ...y };
z = Object.assign({ x }, y);
Via CLI
babel --plugins transform-object-rest-spread script.js
Via Node API
require("babel-core").transform("code", {
plugins: ["transform-object-rest-spread"]
});
References