CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel--plugin-transform-parameters

Babel plugin that compiles ES2015 default and rest parameters to ES5-compatible code

91

1.02x
Overview
Eval results
Files

index.mddocs/

@babel/plugin-transform-parameters

@babel/plugin-transform-parameters is a Babel plugin that automatically transforms ES2015 (ES6) default and rest parameter syntax into ES5-compatible JavaScript code. It enables developers to use modern parameter features while maintaining backwards compatibility with older JavaScript environments.

Package Information

  • Package Name: @babel/plugin-transform-parameters
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-parameters (typically included in @babel/preset-env)

Core Imports

// As a Babel plugin in configuration
module.exports = {
  plugins: ["@babel/plugin-transform-parameters"]
};

For programmatic usage with Babel API:

// CommonJS
const transformParametersPlugin = require("@babel/plugin-transform-parameters").default;

// ES modules  
import transformParametersPlugin from "@babel/plugin-transform-parameters";

// Named export utility (for advanced plugin development)
import { convertFunctionParams } from "@babel/plugin-transform-parameters";

Basic Usage

Babel Configuration

Note: This plugin is typically included automatically when using @babel/preset-env based on your target environment. Manual configuration is only needed for specific use cases.

Add to your Babel configuration file (.babelrc, babel.config.js, etc.):

{
  "plugins": ["@babel/plugin-transform-parameters"]
}

Or with @babel/preset-env (recommended):

{
  "presets": [
    ["@babel/preset-env", {
      "targets": "> 0.25%, not dead"
    }]
  ]
}

With options:

{
  "plugins": [
    ["@babel/plugin-transform-parameters", { "loose": true }]
  ]
}

Transformation Examples

Default Parameters:

// Input (ES6)
function greet(name = "World") {
  console.log(`Hello, ${name}!`);
}

// Output (ES5)
function greet() {
  var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "World";
  console.log("Hello, " + name + "!");
}

Rest Parameters:

// Input (ES6)
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

// Output (ES5)
function sum() {
  for (var _len = arguments.length, numbers = new Array(_len), _key = 0; _key < _len; _key++) {
    numbers[_key] = arguments[_key];
  }
  return numbers.reduce(function(a, b) { return a + b; }, 0);
}

Capabilities

Babel Plugin

The main export provides a Babel plugin that automatically transforms parameter syntax during compilation.

/**
 * Main Babel plugin factory function
 * @param api - Babel API object with version assertion and assumption methods
 * @param options - Plugin configuration options
 * @returns Babel plugin configuration object
 */
export default function(api: BabelAPI, options: Options = {}): BabelPlugin;

interface Options {
  /**
   * Enable loose transformation mode for better performance
   * When true, uses simpler transformations that may not preserve exact ES6 semantics
   */
  loose?: boolean;
}

interface BabelPlugin {
  name: string;
  visitor: {
    Function(path: NodePath<t.Function>): void;
  };
}

Parameter Conversion Utility

Utility function for converting function parameters, used internally and available for other plugins.

/**
 * Convert function parameters with default values and destructuring patterns
 * @param path - Babel AST path to the function node
 * @param ignoreFunctionLength - Whether to ignore function.length property preservation
 * @param shouldTransformParam - Optional predicate to determine which parameters to transform
 * @param replaceRestElement - Optional callback for custom rest element handling
 * @returns Boolean indicating whether any transformations were made
 */
export function convertFunctionParams(
  path: NodePath<t.Function>,
  ignoreFunctionLength: boolean | void,
  shouldTransformParam?: (index: number) => boolean,
  replaceRestElement?: (
    path: NodePath<t.Function>,
    paramPath: NodePath<t.Function["params"][number]>,
    transformedRestNodes: t.Statement[]
  ) => void
): boolean;

/**
 * Internal utility function for converting rest parameters (not part of public API)
 * Used internally by the main plugin to handle rest parameter transformations
 */
function convertFunctionRest(path: NodePath<t.Function>): boolean;

Plugin Behavior

Parameter Types Handled

  1. Default Parameters: function foo(a = 1) {} → argument checking with undefined fallback
  2. Rest Parameters: function foo(...args) {} → arguments object to array conversion
  3. Destructuring Parameters: function foo({x, y}) {} → temporary variable assignment
  4. Combined Patterns: function foo(a = 1, {b}, ...rest) {} → mixed transformation

Arrow Function Conversion

When arrow functions use default or rest parameters, the plugin automatically converts them to regular functions since these features require access to the arguments object:

// Input
const add = (a = 0, b = 0) => a + b;

// Output  
const add = function(a, b) {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  return a + b;
};

Configuration Options

loose: boolean (default: false)

When enabled, generates simpler but less spec-compliant transformations:

// Strict mode (loose: false)
function foo(a = 1) {
  var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
}

// Loose mode (loose: true)
function foo(a) {
  if (a === undefined) {
    a = 1;
  }
}

Assumptions Support

The plugin respects Babel's assumption system:

  • ignoreFunctionLength: Controls whether function.length property is preserved
  • noNewArrows: Controls arrow function transformation behavior

Types

interface Options {
  loose?: boolean;
}

interface BabelAPI {
  assertVersion(version: number | string): void;
  assumption(name: string): any;
}

// Babel AST types namespace
declare namespace t {
  interface Function {
    params: Array<Identifier | Pattern | RestElement>;
    body: BlockStatement | Expression;
    async: boolean;
    generator: boolean;
  }

  interface Statement {
    type: string;
  }

  interface Identifier {
    type: "Identifier";
    name: string;
  }

  interface Pattern {
    type: string;
  }

  interface RestElement {
    type: "RestElement";
    argument: Pattern;
  }

  interface BlockStatement {
    type: "BlockStatement";
    body: Statement[];
  }

  interface Expression {
    type: string;
  }
}

interface NodePath<T = any> {
  node: T;
  scope: Scope;
  get(key: string): NodePath;
  replaceWith(node: any): void;
  isArrowFunctionExpression(): boolean;
  isFunctionExpression(): boolean;
  // ... other Babel NodePath methods
}

interface Scope {
  // Babel scope methods
}

Error Handling

The plugin handles various edge cases:

  • Parameter shadowing: Automatically wraps in IIFE when parameters shadow variables
  • Generator functions: Preserves generator semantics during transformation
  • Async functions: Maintains async behavior with proper error handling
  • Destructuring conflicts: Resolves binding conflicts in complex destructuring patterns

Common transformation errors are handled gracefully, with the plugin falling back to safe transformations when complex patterns are detected.

Install with Tessl CLI

npx tessl i tessl/npm-babel--plugin-transform-parameters

docs

index.md

tile.json