Babel plugin that transforms ES2015 spread syntax into ES5-compatible code
npx @tessl/cli install tessl/npm-babel--plugin-transform-spread@7.27.0@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.
npm install --save-dev @babel/plugin-transform-spread// 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");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 }]]
});The plugin is structured as a standard Babel plugin with these key components:
declare() from @babel/helper-plugin-utilsconstruct, toConsumableArray, maybeArrayLike, and arrayLikeToArrayCreates 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;
}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
});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]);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);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));The plugin includes intelligent optimizations and handles special cases:
// 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);
}// Input
const sparse = [1, , 3];
const spread = [...sparse];
// Output
const sparse = [1, , 3];
const spread = babelHelpers.arrayLikeToArray(sparse);// Input - single spread that's already transformed
const result = [...someTransformedArray];
// Output - optimized to avoid unnecessary array creation
const result = someTransformedArray;The plugin handles specific error conditions:
// 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.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"]
};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 utilitiesCommonly used as part of @babel/preset-env:
// babel.config.js
module.exports = {
presets: [
["@babel/preset-env", {
targets: { ie: "11" }, // Automatically includes spread transform
}]
]
};