@babel/plugin-transform-spread

spread - 图1info

This plugin is included in @babel/preset-env

Example

In

JavaScript

  1. var a = ["a", "b", "c"];
  2. var b = [...a, "foo"];
  3. var c = foo(...a);

Out

JavaScript

  1. var a = ["a", "b", "c"];
  2. var b = a.concat(["foo"]);
  3. var c = foo.apply(void 0, a);

Installation

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

Usage

Without options:

babel.config.json

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

With options:

babel.config.json

  1. {
  2. "plugins": [
  3. [
  4. "@babel/plugin-transform-spread",
  5. {
  6. "loose": true
  7. }
  8. ]
  9. ]
  10. }

Via CLI

Shell

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

Via Node API

JavaScript

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

Options

loose

boolean, defaults to false.

In loose mode, all iterables are assumed to be arrays.

spread - 图2caution

Consider migrating to the top level iterableIsArray assumption.

babel.config.json

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

Under the iterableIsArray assumption, Babel preserves “holes” when spreading an array (for example, [ ...Array(2) ] produces [ (hole), (hole) ]). Set iterableIsArray to false to avoid this behaviour.

spread - 图3tip

You can read more about configuring plugin options here

allowArrayLike

boolean, defaults to false

Added in: v7.10.0

This option allows spreading array-like objects as if they were arrays.

spread - 图4caution

Consider migrating to the top level arrayLikeIsIterable assumption.

babel.config.json

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

An array-like object is an object with a length property: for example, { 0: "a", 1: "b", length: 2 }. Note that, like real arrays, array-like objects can have “holes”: { 1: "a", length: 3 } is equivalent to [ (hole), "a", (hole) ].

While it is not spec-compliant to spread array-like objects as if they were arrays, there are many objects that would be iterables in modern browsers with Symbol.iterator support. Some notable examples are the DOM collections, like document.querySelectorAll("img.big"), which are the main use case for this option.

Please note that Babel allows spreading arguments in old engines even if this option is disabled, because it’s defined as iterable in the ECMAScript specification.

References