or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

@babel/plugin-transform-async-to-generator

@babel/plugin-transform-async-to-generator is a Babel plugin that transforms async functions into ES2015 generators, enabling async/await syntax to work in environments that don't natively support it. The plugin provides comprehensive transformation capabilities with configurable options for method wrapper functions and module imports.

Package Information

  • Package Name: @babel/plugin-transform-async-to-generator
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-async-to-generator
  • Peer Dependencies: @babel/core ^7.0.0-0
  • Node Requirements: >=6.9.0

Core Imports

import plugin from "@babel/plugin-transform-async-to-generator";

For TypeScript types:

import type { Options } from "@babel/plugin-transform-async-to-generator";

Note: This package is published as an ES module. For CommonJS environments, use dynamic import:

const plugin = (await import("@babel/plugin-transform-async-to-generator")).default;

Basic Usage

Default Configuration

Use the plugin with Babel's built-in async-to-generator helper:

// babel.config.js
module.exports = {
  plugins: ["@babel/plugin-transform-async-to-generator"]
};

Custom Module Configuration

Use a custom async wrapper function from an external module:

// babel.config.js
module.exports = {
  plugins: [
    [
      "@babel/plugin-transform-async-to-generator",
      {
        "module": "bluebird",
        "method": "coroutine"
      }
    ]
  ]
};

With Babel Assumptions

Configure the plugin with Babel assumptions for optimized output:

// babel.config.js
module.exports = {
  plugins: ["@babel/plugin-transform-async-to-generator"],
  assumptions: {
    "noNewArrows": false,
    "ignoreFunctionLength": true
  }
};

Capabilities

Plugin Factory Function

The main export that creates a Babel plugin for transforming async functions to generators.

/**
 * Default export: Babel plugin function that transforms async functions into ES2015 generators
 * Created using @babel/helper-plugin-utils declare function
 * @param api - Babel plugin API (from @babel/core)
 * @param options - Plugin configuration options
 * @returns Babel plugin object with visitor pattern
 */
const plugin: (api: object, options: Options) => {
  name: string;
  visitor: {
    Function(path: object, state: object): void;
  };
};

export default plugin;

Transformation Behavior:

  • Identifies async functions that are not already generators (skips functions that are both async and generator)
  • Uses @babel/helper-remap-async-to-generator to perform the AST transformation
  • Converts await expressions to yield expressions
  • When using custom module/method options, imports the specified function using @babel/helper-module-imports
  • In default mode, uses Babel's built-in asyncToGenerator helper
  • Applies Babel assumptions (noNewArrows, ignoreFunctionLength) during transformation

Usage Example:

// Input
async function fetchData() {
  const response = await fetch('/api/data');
  return await response.json();
}

// Output (default mode)
function fetchData() {
  return _asyncToGenerator(function* () {
    const response = yield fetch('/api/data');
    return yield response.json();
  })();
}

// Output (custom module mode with bluebird)
function fetchData() {
  return _bluebird.coroutine(function* () {
    const response = yield fetch('/api/data');
    return yield response.json();
  })();
}

Configuration

Configuration Options

The plugin accepts an Options object to customize the async wrapper function.

Configuration Examples:

// Use bluebird coroutines
{
  "method": "coroutine",
  "module": "bluebird"
}

// Use custom async library
{
  "method": "async",
  "module": "my-async-lib"
}

Babel Assumptions Support

The plugin respects Babel assumptions for optimized output generation:

  • noNewArrows (default: true): When true, avoids creating new arrow functions during transformation. Note: Babel 8 may change this default to false
  • ignoreFunctionLength (default: false): When true, ignores the function.length property during transformation

These assumptions are passed to the internal remapAsyncToGenerator helper function which performs the actual AST transformation.

// babel.config.js with assumptions
module.exports = {
  plugins: ["@babel/plugin-transform-async-to-generator"],
  assumptions: {
    "noNewArrows": false,      // Allow new arrow functions
    "ignoreFunctionLength": true  // Ignore function.length
  }
};

Exported Types

Options Interface

Plugin configuration options interface (exported for TypeScript usage).

/**
 * Configuration options for the async-to-generator transformation
 */
export interface Options {
  /** 
   * Name of the wrapper method to import and use instead of built-in helper
   * Must be used together with 'module' option
   */
  method?: string;
  
  /** 
   * Module name to import the wrapper method from
   * Must be used together with 'method' option
   */
  module?: string;
}

Related Types

The plugin works with standard Babel AST types from @babel/types and visitor patterns from @babel/traverse. The plugin's implementation uses these through the Babel plugin API but does not export them directly.

Error Handling

The plugin includes built-in error handling for common issues:

  • Version Compatibility: Automatically checks Babel version compatibility (requires Babel 7+) using api.assertVersion(REQUIRED_VERSION(7))
  • Function Validation: Automatically skips transformation for functions that are already generators (path.node.generator) or not async (!path.node.async)
  • Configuration Requirements: When using custom wrapper functions, both method and module options must be provided together

The plugin gracefully handles edge cases by returning early from the visitor when transformation is not applicable.

Integration Patterns

Build Tool Integration

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: [
              ['@babel/plugin-transform-async-to-generator', {
                module: 'bluebird',
                method: 'coroutine'
              }]
            ]
          }
        }
      }
    ]
  }
};

Programmatic Usage

import { transformSync } from '@babel/core';
import asyncToGeneratorPlugin from '@babel/plugin-transform-async-to-generator';

const result = transformSync(code, {
  plugins: [
    [asyncToGeneratorPlugin, {
      module: 'bluebird',
      method: 'coroutine'
    }]
  ]
});