CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel--plugin-transform-arrow-functions

Babel plugin that compiles ES2015 arrow functions to ES5 function expressions

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

index.mddocs/

@babel/plugin-transform-arrow-functions

A Babel plugin that compiles ES2015 arrow functions to ES5-compatible function expressions. This plugin is essential for projects that need to support legacy browsers or JavaScript environments that don't natively support ES2015 arrow functions.

Package Information

  • Package Name: @babel/plugin-transform-arrow-functions
  • Package Type: npm (Babel plugin)
  • Language: TypeScript
  • Installation: npm install @babel/plugin-transform-arrow-functions

Core Imports

This package exports a single Babel plugin factory function as the default export:

import arrowFunctionsPlugin from "@babel/plugin-transform-arrow-functions";

For CommonJS:

const arrowFunctionsPlugin = require("@babel/plugin-transform-arrow-functions");

Basic Usage

Add the plugin to your Babel configuration:

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

With options:

{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ]
}

Input:

const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;

Output:

const add = function(a, b) {
  return a + b;
};
const greet = function(name) {
  return `Hello, ${name}!`;
};

Capabilities

Plugin Factory Function

Creates a Babel plugin configuration that transforms arrow functions to regular function expressions.

/**
 * Main plugin factory function that returns a Babel plugin configuration
 * @param api - Babel plugin API object providing transformation utilities
 * @param options - Plugin configuration options
 * @returns PluginObject with visitor methods for AST transformation
 */
export default declare((api: PluginAPI, options: Options) => PluginObject);

export interface Options {
  /** Enable spec-compliant transformation behavior (default: false) */
  spec?: boolean;
}

interface PluginObject {
  /** Plugin identifier */
  name: "transform-arrow-functions";
  /** AST visitor methods */
  visitor: {
    ArrowFunctionExpression(path: NodePath<ArrowFunctionExpression>): void;
  };
}

Usage Example:

import { declare } from "@babel/helper-plugin-utils";

// The plugin is created using Babel's declare function
const plugin = declare((api, options) => {
  api.assertVersion(REQUIRED_VERSION(7));
  
  const noNewArrows = api.assumption("noNewArrows") ?? !options.spec;
  
  return {
    name: "transform-arrow-functions",
    visitor: {
      ArrowFunctionExpression(path) {
        // In some conversion cases, it may have already been converted to a function
        if (!path.isArrowFunctionExpression()) return;
        
        // Handle Babel 8 breaking changes vs backward compatibility
        if (process.env.BABEL_8_BREAKING) {
          path.arrowFunctionToExpression({
            allowInsertArrow: false,
            noNewArrows,
          });
        } else {
          path.arrowFunctionToExpression({
            allowInsertArrow: false,
            noNewArrows,
            specCompliant: !noNewArrows, // Backward compat with @babel/traverse <7.13.0
          });
        }
      }
    }
  };
});

Configuration Options

spec Option

Controls spec-compliant transformation behavior.

interface Options {
  /**
   * Enable spec-compliant transformation behavior
   * - When true: ensures strict ES5 compatibility
   * - When false: allows optimizations that may not be strictly spec-compliant
   * @default false
   */
  spec?: boolean;
}

Usage:

{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ]
}

Transformation Behavior

Standard Transformation

Arrow functions are converted to regular function expressions while preserving semantics:

  • Lexical this binding: Arrow functions inherit this from enclosing scope
  • No arguments object: Arrow functions don't have their own arguments
  • Cannot be used as constructors: Arrow functions cannot be called with new

Spec Compliance

When spec: true is enabled, the plugin ensures spec-compliant transformation behavior:

  • Enables stricter adherence to ECMAScript specifications
  • Affects the noNewArrows setting (when spec: true, noNewArrows defaults to false)
  • Provides backward compatibility with older Babel versions

Babel Assumptions

The plugin respects Babel's noNewArrows assumption and interacts with the spec option:

/**
 * noNewArrows assumption calculation
 * @formula noNewArrows = api.assumption("noNewArrows") ?? !options.spec
 * @behavior When spec: true, noNewArrows defaults to false (more defensive)
 * @behavior When spec: false, noNewArrows defaults to true (more optimized)
 */

Assumption Behaviors:

  • When noNewArrows is true: Optimizes transformations assuming no new arrow functions are inserted during the transformation process
  • When noNewArrows is false: Uses more defensive transformations that can handle cases where new arrow functions might be inserted
  • Default with spec: true: noNewArrows = false (defensive, spec-compliant)
  • Default with spec: false: noNewArrows = true (optimized, may not be fully spec-compliant)

Example Configurations:

// Spec-compliant mode (defensive)
{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ],
  "assumptions": {
    "noNewArrows": false  // ← Automatically set by spec: true
  }
}

// Optimized mode (faster but less defensive)
{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": false }]
  ],
  "assumptions": {
    "noNewArrows": true   // ← Automatically set by spec: false
  }
}

// Explicit override
{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ],
  "assumptions": {
    "noNewArrows": true   // ← Overrides spec: true default
  }
}

Dependencies

Peer Dependencies

/**
 * Required Babel core version
 * @requirement "@babel/core": "^7.0.0-0"
 */

Helper Dependencies

/**
 * Babel plugin utilities
 * @dependency "@babel/helper-plugin-utils"
 */
import { declare } from "@babel/helper-plugin-utils";

/**
 * Global version requirement function
 * @global REQUIRED_VERSION - Ensures Babel version compatibility
 */
declare function REQUIRED_VERSION(version: number): string;

Browser and Environment Support

  • Node.js: ≥6.9.0
  • Babel Version: ≥7.0.0-0
  • Module Type: ES Module (supports both ESM and CommonJS)
  • Target Environments: Converts ES2015+ arrow functions to ES5-compatible code

Super Usage Limitations

The plugin has specific limitations when transforming arrow functions that contain super usage:

Super Call Limitations

/**
 * Error: Arrow functions with super() calls cannot be transformed without class transform
 * @throws "When using '@babel/plugin-transform-arrow-functions', it's not possible to compile `super()` in an arrow function without compiling classes.\nPlease add '@babel/plugin-transform-classes' to your Babel configuration."
 */

Problematic Code:

class Parent {
  constructor() {
    const fn = () => super(); // ❌ Error: super() in arrow function
  }
}

Solution: Add @babel/plugin-transform-classes to your Babel configuration:

{
  "plugins": [
    "@babel/plugin-transform-classes",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Super Property Limitations

/**
 * Error: Arrow functions with super.property access cannot be transformed without class transform
 * @throws "When using '@babel/plugin-transform-arrow-functions', it's not possible to compile `super.prop` in an arrow function without compiling classes.\nPlease add '@babel/plugin-transform-classes' to your Babel configuration."
 */

Problematic Code:

class Child extends Parent {
  method() {
    const fn = () => super.parentMethod(); // ❌ Error: super.prop in arrow function
  }
}

Plugin Interaction Requirements

This plugin requires specific other plugins when transforming certain code patterns:

Class Transform Dependency

When arrow functions contain super() calls or super.property access, you must include @babel/plugin-transform-classes:

{
  "plugins": [
    "@babel/plugin-transform-classes",      // ← Required for super usage
    "@babel/plugin-transform-arrow-functions"
  ]
}

Plugin Ordering

The order of plugins matters for optimal transformation:

{
  "plugins": [
    "transform-parameters",        // ← Process parameters first
    "transform-arrow-functions"    // ← Then transform arrow functions
  ]
}

Error Handling

The plugin includes built-in error handling for:

  • Version compatibility: Asserts minimum Babel version using api.assertVersion()
  • Invalid transformations: Validates arrow function expressions before transformation
  • Configuration errors: Handles invalid plugin options gracefully
  • Super usage: Throws descriptive errors for unsupported super patterns
  • Plugin dependencies: Provides clear error messages when required plugins are missing

Common Errors and Solutions

Babel Version Error:

# Error: Babel version too old
# Solution: Upgrade to Babel 7.0.0 or higher
npm install @babel/core@^7.0.0

Configuration Error:

{
  "plugins": [
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]  // ✓ Valid
    // ["@babel/plugin-transform-arrow-functions", { "invalid": true }]  // ❌ Invalid
  ]
}

Super Usage Errors:

// ❌ Problem: Arrow function with super() without class transform
class MyClass extends Parent {
  method() {
    const fn = () => super();
  }
}

// ✓ Solution: Add @babel/plugin-transform-classes
{
  "plugins": [
    "@babel/plugin-transform-classes",
    "@babel/plugin-transform-arrow-functions"
  ]
}

docs

index.md

tile.json