or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

@babel/plugin-transform-spread

@babel/plugin-transform-spread is a Babel plugin that transforms ES2015 spread syntax (...) into ES5-compatible code. It handles spread operations in array literals, function calls, and constructor calls, providing configurable transformation options for different compatibility requirements.

Package Information

  • Package Name: @babel/plugin-transform-spread
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-spread

Core Imports

// Default import (plugin factory function)
import transformSpread from "@babel/plugin-transform-spread";

// Named import for types (TypeScript only)
import type { Options } from "@babel/plugin-transform-spread";

For CommonJS:

const transformSpread = require("@babel/plugin-transform-spread");

Basic Usage

import { transformSync } from "@babel/core";
import transformSpread from "@babel/plugin-transform-spread";

// Basic plugin usage
const result = transformSync(`
  const array = [1, 2, 3];
  const newArray = [0, ...array, 4];
  function myFunc(...args) { console.log(args); }
  myFunc(...newArray);
`, {
  plugins: [transformSpread]
});

// With options
const resultWithOptions = transformSync(code, {
  plugins: [[transformSpread, { allowArrayLike: true, loose: false }]]
});

Architecture

The plugin is structured as a standard Babel plugin with these key components:

  • Plugin Factory Function: Main export that creates a configured Babel plugin using declare() from @babel/helper-plugin-utils
  • AST Visitors: Three specialized visitors for different spread syntax contexts (ArrayExpression, CallExpression, NewExpression)
  • Transformation Logic: Internal functions that convert spread operations to ES5-compatible code
  • Babel Helpers: Uses runtime helpers like construct, toConsumableArray, maybeArrayLike, and arrayLikeToArray
  • Configuration Options: Interface for customizing transformation behavior through options and Babel assumptions

Capabilities

Plugin Factory Function

Creates a configured Babel plugin instance with custom options.

/**
 * Main export: Babel plugin factory function created using declare() helper
 * from @babel/helper-plugin-utils
 * @param api - Babel API object providing utilities and version checking
 * @param options - Configuration options for the transformation
 * @returns Babel plugin configuration object
 */
export default declare((api: BabelAPI, options: Options) => BabelPlugin);

interface BabelAPI {
  assertVersion(version: number): void;
  assumption(name: "iterableIsArray" | "arrayLikeIsIterable"): boolean | undefined;
}

interface BabelPlugin {
  name: "transform-spread";
  visitor: {
    ArrayExpression(path: NodePath): void;
    CallExpression(path: NodePath): void;
    NewExpression(path: NodePath): void;
  };
}

interface NodePath {
  node: any;
  scope: Scope;
  buildCodeFrameError(message: string): Error;
  replaceWith(node: any): void;
  get(key: string): NodePath;
  hub: any;
}

interface Scope {
  buildUndefinedNode(): any;
  getBinding(name: string): any;
  maybeGenerateMemoised(node: any): any;
  path: NodePath;
}

/**
 * Configuration options interface - also available as a named export
 */
export interface Options {
  allowArrayLike?: boolean;
  loose?: boolean;
}

Configuration Options

Options interface for customizing plugin behavior.

interface Options {
  /**
   * Allow transforming array-like objects (arguments object, etc.)
   * When true, enables transformation of array-like objects to arrays
   * @default false
   */
  allowArrayLike?: boolean;
  
  /**
   * Enable loose mode for simpler output code
   * When true, assumes iterables are arrays for performance
   * @default false
   */
  loose?: boolean;
}

Usage Examples:

// Default configuration (strict mode)
const plugin = transformSpread(api, {});

// Allow array-like objects
const pluginWithArrayLike = transformSpread(api, { 
  allowArrayLike: true 
});

// Loose mode for performance
const pluginLoose = transformSpread(api, { 
  loose: true 
});

// Combined options
const pluginCombined = transformSpread(api, {
  allowArrayLike: true,
  loose: false
});

Array Expression Transformation

Transforms spread elements in array literals to ES5-compatible concatenation.

Input:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [0, ...arr1, ...arr2, 5];

Output:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [0].concat(babelHelpers.toConsumableArray(arr1), babelHelpers.toConsumableArray(arr2), [5]);

Call Expression Transformation

Transforms spread arguments in function calls to use .apply() method.

Input:

function myFunc(a, b, c) { return a + b + c; }
const args = [1, 2, 3];
const result = myFunc(...args);

Output:

function myFunc(a, b, c) { return a + b + c; }
const args = [1, 2, 3];
const result = myFunc.apply(void 0, args);

Method Call Context:

// Input
obj.method(...args);

// Output  
var _obj;
(_obj = obj).method.apply(_obj, args);

New Expression Transformation

Transforms spread arguments in constructor calls using a helper function.

Input:

class MyClass {
  constructor(a, b, c) {
    this.values = [a, b, c];
  }
}
const args = [1, 2, 3];
const instance = new MyClass(...args);

Output:

// Uses Babel's "construct" helper function
const instance = babelHelpers.construct(MyClass, babelHelpers.toConsumableArray(args));

Special Cases and Optimizations

The plugin includes intelligent optimizations and handles special cases:

Arguments Object Handling

// Input
function wrapper() {
  return otherFunc(...arguments);
}

// Output (standard mode)
function wrapper() {
  return otherFunc.apply(void 0, Array.prototype.slice.call(arguments));
}

// Output (loose mode with iterableIsArray assumption)
function wrapper() {
  return otherFunc.apply(void 0, arguments);
}

Array Hole Handling

// Input
const sparse = [1, , 3];
const spread = [...sparse];

// Output
const sparse = [1, , 3];
const spread = babelHelpers.arrayLikeToArray(sparse);

Single Spread Optimization

// Input - single spread that's already transformed
const result = [...someTransformedArray];

// Output - optimized to avoid unnecessary array creation
const result = someTransformedArray;

Error Handling

The plugin handles specific error conditions:

Super Call Limitation

// This will throw a compilation error
class Child extends Parent {
  constructor(...args) {
    super(...args); // Error: requires @babel/plugin-transform-classes
  }
}

Error Message:

It's not possible to compile spread arguments in `super()` without compiling classes.
Please add '@babel/plugin-transform-classes' to your Babel configuration.

Assumptions Integration

The plugin integrates with Babel's assumption system:

// babel.config.js
module.exports = {
  assumptions: {
    "iterableIsArray": true,      // Equivalent to loose: true
    "arrayLikeIsIterable": true   // Equivalent to allowArrayLike: true
  },
  plugins: ["@babel/plugin-transform-spread"]
};

Babel Helpers

The plugin generates calls to Babel runtime helpers. These are automatically included when using @babel/runtime:

// Helper functions used by the plugin
babelHelpers.construct(constructor: Function, args: any[]): any;
babelHelpers.toConsumableArray(arr: any): any[];
babelHelpers.maybeArrayLike(helper: Function, arr: any): any[];
babelHelpers.arrayLikeToArray(arr: ArrayLike<any>): any[];

Dependencies:

  • @babel/helper-plugin-utils: Provides the declare() function
  • @babel/helper-skip-transparent-expression-wrappers: For AST traversal utilities

Compatibility

  • Node.js: >= 6.9.0
  • Babel: >= 7.0.0-0
  • Output Target: ES5-compatible JavaScript
  • Source Support: ES2015+ with spread syntax

Integration with Babel Presets

Commonly used as part of @babel/preset-env:

// babel.config.js
module.exports = {
  presets: [
    ["@babel/preset-env", {
      targets: { ie: "11" }, // Automatically includes spread transform
    }]
  ]
};