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

object-rest-spread - 图1info

This plugin is included in @babel/preset-env, in ES2018

Example

Rest Properties

JavaScript

  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

JavaScript

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

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-object-rest-spread
  1. yarn add --dev @babel/plugin-transform-object-rest-spread
  1. pnpm add --save-dev @babel/plugin-transform-object-rest-spread

Usage

babel.config.json

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

Via CLI

Shell

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

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-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).

object-rest-spread - 图2caution

Consider migrating to the top level setSpreadProperties assumption.

babel.config.json

  1. {
  2. "assumptions": {
  3. "setSpreadProperties": true
  4. }
  5. }

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

JSON

  1. {
  2. "assumptions": {
  3. "setSpreadProperties": true
  4. },
  5. "plugins": [
  6. ["@babel/plugin-transform-object-rest-spread", { "useBuiltIns": true }]
  7. ]
  8. }

In

JavaScript

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

Out

JavaScript

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

object-rest-spread - 图3tip

You can read more about configuring plugin options here

References