CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel-plugin-transform-es2015-destructuring

Babel plugin that transforms ES2015 destructuring assignment syntax into ES5-compatible code

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Babel Plugin Transform ES2015 Destructuring

babel-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.

Package Information

  • Package Name: babel-plugin-transform-es2015-destructuring
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install --save-dev babel-plugin-transform-es2015-destructuring

Core Imports

The 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.

Basic Usage

Via .babelrc (Recommended)

{
  "plugins": ["transform-es2015-destructuring"]
}

Via CLI

babel --plugins transform-es2015-destructuring script.js

Via Node API

require("babel-core").transform("code", {
  plugins: ["transform-es2015-destructuring"]
});

Architecture

The plugin employs several optimization strategies for efficient destructuring transformation:

  • Array Unpacking Optimization: When possible, simple array destructuring is optimized to direct element access rather than using runtime helpers
  • Static Analysis: Uses scope analysis to detect variable references and optimize array unpacking decisions
  • Lazy Evaluation: For complex destructuring patterns, generates temporary variables only when necessary to avoid multiple evaluations
  • Pattern Recognition: Distinguishes between object patterns, array patterns, assignment patterns, and rest patterns to apply appropriate transformations

Capabilities

Plugin Factory Function

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:

Visitor Methods

ExportNamedDeclaration

Handles destructuring patterns in export declarations.

/**
 * Transforms destructuring in export named declarations
 * @param {Object} path - Babel path object for the ExportNamedDeclaration node
 */
ExportNamedDeclaration(path);

ForXStatement

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);

CatchClause

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);

AssignmentExpression

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);

VariableDeclaration

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);

DestructuringTransformer Class

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);
}

Utility Functions

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);

Array Unpacking Visitor

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);
};

Transformation Examples

The plugin transforms various forms of ES2015 destructuring:

Object Destructuring

Input:

var { x, y } = coords;

Output:

var x = coords.x,
    y = coords.y;

Array Destructuring

Input:

const [first, second] = arr;

Output:

var _arr = arr;
var first = _arr[0];
var second = _arr[1];

Assignment Patterns (Default Values)

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;

Rest Patterns

Input:

const { a, ...rest } = obj;

Output:

var _obj = obj;
var a = _obj.a;
var rest = _objectWithoutProperties(_obj, ["a"]);

Nested Destructuring

Input:

const { user: { name, age } } = data;

Output:

var _data = data;
var _user = _data.user;
var name = _user.name;
var age = _user.age;

Error Handling

The plugin operates within Babel's transformation pipeline and relies on Babel's error handling mechanisms. Common scenarios include:

  • Invalid AST nodes: The plugin gracefully handles non-destructuring patterns by checking node types before transformation
  • Missing dependencies: Requires babel-runtime for helper functions like objectWithoutProperties
  • Scope conflicts: Uses Babel's scope analysis to generate unique identifiers and avoid naming conflicts

If the plugin encounters unsupported syntax or missing dependencies, Babel will throw appropriate compilation errors.

Dependencies

  • babel-runtime: ^6.22.0 - Provides runtime helpers for Babel transformations

Integration Notes

This plugin is designed to work within the Babel 6.x ecosystem and expects:

  • Access to Babel's types API for AST node creation and testing
  • Integration with Babel's visitor pattern for AST traversal
  • Access to Babel scope and file objects for context and helper functions
  • Babel helper functions like objectWithoutProperties and objectDestructuringEmpty

The 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.

Known Source Code Issues

  • Line 209: canUnpackArrayPattern method has a missing return false statement, which causes the method to return undefined instead of false in some cases
  • buildVariableDeclaration behavior: Always generates var declarations regardless of the kind parameter passed to the constructor
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/babel-plugin-transform-es2015-destructuring@6.23.x
Publish Source
CLI
Badge
tessl/npm-babel-plugin-transform-es2015-destructuring badge