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

Example

Rest Properties

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

Spread Properties

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

Installation

  1. npm install --save-dev @babel/plugin-proposal-object-rest-spread

Usage

  1. {
  2. "plugins": ["@babel/plugin-proposal-object-rest-spread"]
  3. }

Via CLI

  1. babel --plugins @babel/plugin-proposal-object-rest-spread script.js

Via Node API

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

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).

:warning: 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

  1. {
  2. "plugins": [
  3. ["@babel/plugin-proposal-object-rest-spread", { "loose": true, "useBuiltIns": true }]
  4. ]
  5. }

In

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

Out

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

You can read more about configuring plugin options here

References