Babel plugin that transforms ES2015 destructuring assignment syntax into ES5-compatible code
npx @tessl/cli install tessl/npm-babel-plugin-transform-es2015-destructuring@6.23.0babel-plugin-transform-es2015-destructuring is a Babel plugin that transforms ES2015 (ES6) destructuring assignment syntax into ES5-compatible code. This enables modern destructuring features like array and object destructuring in older JavaScript environments that don't support ES2015+ syntax.
npm install --save-dev babel-plugin-transform-es2015-destructuringThe plugin exports a single default function that integrates with Babel's plugin system:
// Plugin registration (internal usage)
export default function ({ types: t }) { ... }This plugin is not typically imported directly in user code. Instead, it's configured through Babel configuration files.
{
"plugins": ["transform-es2015-destructuring"]
}babel --plugins transform-es2015-destructuring script.jsrequire("babel-core").transform("code", {
plugins: ["transform-es2015-destructuring"]
});The plugin employs several optimization strategies for efficient destructuring transformation:
The main export that creates the Babel plugin.
/**
* Creates a Babel plugin for transforming ES2015 destructuring syntax
* @param {Object} babel - Babel instance with types API
* @param {Object} babel.types - Babel types API for AST manipulation
* @returns {Object} Plugin object with visitor methods
*/
function transformES2015Destructuring({ types: t });The returned plugin object contains a visitor property with the following AST visitor methods:
Handles destructuring patterns in export declarations.
/**
* Transforms destructuring in export named declarations
* @param {Object} path - Babel path object for the ExportNamedDeclaration node
*/
ExportNamedDeclaration(path);Handles destructuring patterns in for-in and for-of loop statements.
/**
* Transforms destructuring in for-in and for-of statements
* @param {Object} path - Babel path object for the ForXStatement node
* @param {Object} file - Babel file object for the current file being processed
*/
ForXStatement(path, file);Handles destructuring patterns in catch clause parameters.
/**
* Transforms destructuring in catch clause parameters
* @param {Object} pathInfo - Destructured path information containing node and scope
* @param {Object} pathInfo.node - The CatchClause AST node
* @param {Object} pathInfo.scope - Babel scope object for the catch clause
* @param {Object} file - Babel file object for the current file being processed
*/
CatchClause({ node, scope }, file);Handles destructuring patterns in assignment expressions.
/**
* Transforms destructuring in assignment expressions
* @param {Object} path - Babel path object for the AssignmentExpression node
* @param {Object} file - Babel file object for the current file being processed
*/
AssignmentExpression(path, file);Handles destructuring patterns in variable declarations.
/**
* Transforms destructuring in variable declarations
* @param {Object} path - Babel path object for the VariableDeclaration node
* @param {Object} file - Babel file object for the current file being processed
*/
VariableDeclaration(path, file);Internal class that performs the actual destructuring transformations.
/**
* Core class for transforming destructuring patterns into ES5-compatible code
*/
class DestructuringTransformer {
/**
* Creates a new DestructuringTransformer instance
* @param {Object} opts - Configuration options
* @param {number} opts.blockHoist - Block hoisting level for generated statements
* @param {string} opts.operator - Assignment operator for transformations
* @param {Array} opts.nodes - Array to collect generated AST nodes (defaults to empty array)
* @param {Object} opts.scope - Babel scope object for variable management
* @param {Object} opts.file - Babel file object for helper access
* @param {string} opts.kind - Variable declaration kind ('var', 'let', 'const')
*
* @description The constructor also initializes an internal arrays property for tracking array references
*/
constructor(opts);
/**
* Builds a variable assignment or expression statement
* @param {Object} id - AST node for the assignment target
* @param {Object} init - AST node for the assignment value
* @returns {Object} AST node for the variable assignment
*/
buildVariableAssignment(id, init);
/**
* Builds a variable declaration with 'var' kind
* @param {Object} id - AST node for the variable identifier
* @param {Object} init - AST node for the variable initializer
* @returns {Object} AST node for the variable declaration
* @note Always uses "var" kind regardless of the constructor's kind parameter
*/
buildVariableDeclaration(id, init);
/**
* Dispatches pattern processing to appropriate handler method
* @param {Object} id - AST node for the destructuring pattern
* @param {Object} init - AST node for the destructuring source
*/
push(id, init);
/**
* Converts expression to array form for iteration
* @param {Object} node - AST node to convert to array
* @param {number} count - Optional count for array conversion optimization
* @returns {Object} AST node representing array conversion
*/
toArray(node, count);
/**
* Handles assignment patterns with default values
* @param {Object} pattern - AssignmentPattern AST node
* @param {Object} valueRef - AST node for the value reference
*/
pushAssignmentPattern(pattern, valueRef);
/**
* Handles object rest properties in destructuring
* @param {Object} pattern - ObjectPattern AST node
* @param {Object} objRef - AST node for the object reference
* @param {Object} spreadProp - RestProperty AST node
* @param {number} spreadPropIndex - Index of the rest property
*/
pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex);
/**
* Processes individual object properties in destructuring
* @param {Object} prop - Property AST node from ObjectPattern
* @param {Object} propRef - AST node for the property reference
*/
pushObjectProperty(prop, propRef);
/**
* Handles complete object destructuring patterns
* @param {Object} pattern - ObjectPattern AST node
* @param {Object} objRef - AST node for the object reference
*/
pushObjectPattern(pattern, objRef);
/**
* Determines if array pattern can be optimally unpacked
* @param {Object} pattern - ArrayPattern AST node
* @param {Object} arr - ArrayExpression AST node
* @returns {boolean} True if unpacking optimization is safe
* @note Source code contains a bug at line 209: missing return false statement
*/
canUnpackArrayPattern(pattern, arr);
/**
* Optimally processes array patterns that can be unpacked
* @param {Object} pattern - ArrayPattern AST node
* @param {Object} arr - ArrayExpression AST node
*/
pushUnpackedArrayPattern(pattern, arr);
/**
* Handles array destructuring patterns
* @param {Object} pattern - ArrayPattern AST node
* @param {Object} arrayRef - AST node for the array reference
*/
pushArrayPattern(pattern, arrayRef);
/**
* Initializes the destructuring transformation process
* @param {Object} pattern - Destructuring pattern AST node
* @param {Object} ref - Reference AST node for the destructuring source
* @returns {Array} Array of generated AST nodes for the transformation
*/
init(pattern, ref);
}Helper functions used internally by the plugin.
/**
* Tests if a VariableDeclaration contains any destructuring patterns
* @param {Object} node - VariableDeclaration AST node to test
* @returns {boolean} True if the declaration contains destructuring patterns
*/
function variableDeclarationHasPattern(node);
/**
* Tests if an ArrayPattern contains any RestElements
* @param {Object} pattern - ArrayPattern AST node to test
* @returns {boolean} True if the pattern contains rest elements
*/
function hasRest(pattern);Internal visitor used for static analysis during array unpacking optimization.
/**
* Internal visitor for detecting variable references during array unpacking optimization
* Used to determine if array destructuring can be safely optimized to direct element access
*/
const arrayUnpackVisitor = {
/**
* Checks for referenced identifiers that would prevent array unpacking optimization
* @param {Object} path - Babel path object for the ReferencedIdentifier node
* @param {Object} state - State object containing bindings and deopt flag
* @param {Object} state.bindings - Object mapping variable names to binding information
* @param {boolean} state.deopt - Flag indicating if optimization should be disabled
*/
ReferencedIdentifier(path, state);
};The plugin transforms various forms of ES2015 destructuring:
Input:
var { x, y } = coords;Output:
var x = coords.x,
y = coords.y;Input:
const [first, second] = arr;Output:
var _arr = arr;
var first = _arr[0];
var second = _arr[1];Input:
const { a = 1, b = 2 } = obj;Output:
var _obj = obj;
var a = _obj.a === undefined ? 1 : _obj.a;
var b = _obj.b === undefined ? 2 : _obj.b;Input:
const { a, ...rest } = obj;Output:
var _obj = obj;
var a = _obj.a;
var rest = _objectWithoutProperties(_obj, ["a"]);Input:
const { user: { name, age } } = data;Output:
var _data = data;
var _user = _data.user;
var name = _user.name;
var age = _user.age;The plugin operates within Babel's transformation pipeline and relies on Babel's error handling mechanisms. Common scenarios include:
babel-runtime for helper functions like objectWithoutPropertiesIf the plugin encounters unsupported syntax or missing dependencies, Babel will throw appropriate compilation errors.
This plugin is designed to work within the Babel 6.x ecosystem and expects:
types API for AST node creation and testingobjectWithoutProperties and objectDestructuringEmptyThe plugin processes destructuring patterns found in variable declarations, assignment expressions, for-loop declarations, catch clause parameters, and export declarations, converting them into equivalent ES5-compatible code that can run in older JavaScript environments.
canUnpackArrayPattern method has a missing return false statement, which causes the method to return undefined instead of false in some casesbuildVariableDeclaration behavior: Always generates var declarations regardless of the kind parameter passed to the constructor