CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel--plugin-transform-regenerator

Babel plugin that transforms async and generator functions into regenerator-runtime-based state machines.

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-regenerator

A Babel plugin that transforms async and generator functions into regenerator-runtime-based state machines, enabling modern JavaScript async/await and generator syntax to work in environments that don't natively support these features.

Package Information

  • Package Name: @babel/plugin-transform-regenerator
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-regenerator

Core Imports

// ES Module
import transformRegeneratorPlugin from "@babel/plugin-transform-regenerator";

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

Basic Usage

Babel Configuration

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

With options:

{
  "plugins": [
    ["@babel/plugin-transform-regenerator", {
      "async": true,
      "generators": true,
      "asyncGenerators": true
    }]
  ]
}

Programmatic Usage

import babel from "@babel/core";
import transformRegeneratorPlugin from "@babel/plugin-transform-regenerator";

const result = babel.transform(code, {
  plugins: [transformRegeneratorPlugin]
});

Capabilities

Plugin Function

The main plugin export that provides async and generator function transformation. The plugin is created using @babel/helper-plugin-utils's declare function.

/**
 * Babel plugin that transforms async and generator functions into state machines
 * Created using @babel/helper-plugin-utils declare() with visitor pattern
 */
function transformRegeneratorPlugin(): BabelPluginObj;
export default transformRegeneratorPlugin;

interface BabelPluginObj {
  name: "transform-regenerator";
  visitor: {
    Method(path: NodePath, state: PluginPass): void;
    Function: {
      exit(path: NodePath, state: PluginPass): void;
    };
  };
}

interface PluginPass {
  opts: PluginOptions;
  addHelper(name: string): t.Expression;
  availableHelper?(name: string): boolean;
}

Plugin Configuration Options

Configure which types of functions to transform.

interface PluginOptions {
  /** Enable/disable transformation of async functions (default: true) */
  async?: boolean;
  /** Enable/disable transformation of generator functions (default: true) */
  generators?: boolean;
  /** Enable/disable transformation of async generator functions (default: true) */
  asyncGenerators?: boolean;
}

Usage Examples:

// Transform only async functions
{
  "plugins": [
    ["@babel/plugin-transform-regenerator", {
      "async": true,
      "generators": false,
      "asyncGenerators": false
    }]
  ]
}

// Transform only generators
{
  "plugins": [
    ["@babel/plugin-transform-regenerator", {
      "async": false,
      "generators": true,
      "asyncGenerators": false
    }]
  ]
}

// Default: transform all types
{
  "plugins": ["@babel/plugin-transform-regenerator"]
}

Transformation Behavior

The plugin performs the following transformations:

Async Functions

Transforms async functions into regenerator-runtime state machines with Promise handling:

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

// Output (with modern helpers)
function fetchData() {
  return babelHelpers.regeneratorAsync(function fetchData$(_context) {
    while (1) {
      switch (_context.n) {
        case 0:
          _context.n = 1;
          return babelHelpers.awaitAsyncGenerator(fetch('/api/data'));
        case 1:
          response = _context.v;
          return _context.a(2, response.json());
        case 2:
        case "end":
          return _context.stop();
      }
    }
  }, null, null, null, Promise);
}

Generator Functions

Transforms generator functions into regenerator-runtime state machines with iterator protocol:

// Input
function* numbers() {
  yield 1;
  yield 2;
  yield 3;
}

// Output (with modern helpers)
var _marked = /*#__PURE__*/babelHelpers.regenerator().m(numbers);

function numbers() {
  return babelHelpers.regenerator().w(function numbers$(_context) {
    while (1) {
      switch (_context.n) {
        case 0:
          _context.n = 1;
          return 1;
        case 1:
          _context.n = 2;
          return 2;
        case 2:
          _context.n = 3;
          return 3;
        case 3:
        case "end":
          return _context.stop();
      }
    }
  }, _marked);
}

Async Generator Functions

Combines both async and generator transformation patterns:

// Input
async function* asyncNumbers() {
  yield await Promise.resolve(1);
  yield await Promise.resolve(2);
}

// Output (with modern helpers)
function asyncNumbers() {
  return babelHelpers.regeneratorAsyncGen(function asyncNumbers$(_context) {
    while (1) {
      switch (_context.n) {
        case 0:
          _context.n = 1;
          return babelHelpers.awaitAsyncGenerator(Promise.resolve(1));
        case 1:
          _context.n = 2;
          return _context.v;
        case 2:
          _context.n = 3;
          return babelHelpers.awaitAsyncGenerator(Promise.resolve(2));
        case 3:
          _context.n = 4;
          return _context.v;
        case 4:
        case "end":
          return _context.stop();
      }
    }
  }, null, null, null, Promise);
}

Dependencies

Runtime Dependencies

  • @babel/helper-plugin-utils: workspace:^ - Provides the declare function for plugin creation

Peer Dependencies

  • @babel/core: ^7.0.0-0 - Required for plugin operation and AST manipulation

Helper Dependencies

The plugin uses different helper functions depending on the Babel version:

Modern Babel (@babel/helpers >= 7.18.0):

  • regenerator() - Main regenerator helper that provides .m(), .w(), .a() methods
  • regeneratorAsync - For async function transformations
  • regeneratorAsyncGen - For async generator function transformations
  • awaitAsyncGenerator - For await expression transformations

Legacy Babel:

  • regeneratorRuntime - Global runtime with .mark(), .wrap(), .async(), .awrap() methods

Additional Requirements

The transformed code requires regenerator-runtime to be available at runtime. This can be provided through:

  • @babel/polyfill (deprecated)
  • @babel/runtime with @babel/plugin-transform-runtime
  • Manual inclusion of regenerator-runtime package
  • @babel/preset-env with appropriate polyfill configuration
// Manual runtime inclusion
import "regenerator-runtime/runtime";

// Or with @babel/plugin-transform-runtime
{
  "plugins": [
    "@babel/plugin-transform-regenerator",
    ["@babel/plugin-transform-runtime", {
      "regenerator": true
    }]
  ]
}

// Or using babel-plugin-polyfill-regenerator
{
  "plugins": [
    "@babel/plugin-transform-regenerator",
    ["babel-plugin-polyfill-regenerator", {
      "method": "usage-global"
    }]
  ]
}

Version-Specific Behavior

The plugin's output varies based on the Babel version and helper availability:

Babel 8 (BABEL_8_BREAKING mode):

  • Uses modern helpers: regenerator(), regeneratorAsync, regeneratorAsyncGen
  • Output uses abbreviated method names: .m(), .w(), .a(), .n, .v
  • Cleaner generated code with improved helper integration

Babel 7 (Legacy mode):

  • Falls back to regeneratorRuntime global object
  • Uses full method names: .mark(), .wrap(), .async(), .awrap()
  • Requires explicit runtime polyfill setup

Integration with Other Babel Plugins

This plugin is commonly used with:

  • @babel/preset-env: Automatically includes this plugin based on target environments
  • @babel/plugin-transform-runtime: Provides regenerator-runtime without global pollution
  • @babel/plugin-proposal-function-sent: Supports function.sent meta-property in generators
  • babel-plugin-polyfill-regenerator: Modern alternative for polyfill injection

Error Handling

The plugin handles various edge cases during transformation:

  • Nested Functions: Only transforms the appropriate scopes
  • Variable Hoisting: Properly hoists variable declarations from function bodies
  • This Binding: Preserves this context in transformed functions
  • Arguments Object: Handles arguments object references in transformed functions
  • Exception Handling: Maintains try/catch/finally semantics in state machines

Common transformation errors are related to:

  • Missing regenerator-runtime at execution time
  • Conflicts with other async/generator transformations
  • Issues with complex control flow patterns

Browser and Environment Support

This plugin enables async/generator support in:

  • Legacy Browsers: IE11, older Chrome/Firefox/Safari versions
  • Node.js: Older Node.js versions without native async/await
  • React Native: Environments with limited JavaScript feature support
  • Embedded JavaScript: V8 isolates or other restricted environments

The generated code is ES5-compatible when regenerator-runtime is available.

docs

index.md

tile.json