CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel-plugin-transform-runtime

Babel plugin that externalizes helpers and built-ins to prevent global pollution while providing ES6+ feature support

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

babel-plugin-transform-runtime is a Babel plugin that transforms code to externalize references to helpers and built-in polyfills, preventing global pollution while providing ES6+ feature support. It automatically requires babel-runtime modules for regenerator functions, core-js polyfills for built-ins like Promise, Map, Set, and Symbol, and replaces inline Babel helpers with modular imports from babel-runtime/helpers.

Package Information

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

Core Imports

// The plugin is imported automatically by Babel when configured
// No direct imports needed in application code

For programmatic usage:

const babel = require("babel-core");
const transformRuntime = require("babel-plugin-transform-runtime");

Basic Usage

Via .babelrc (Recommended)

{
  "plugins": ["transform-runtime"]
}

With Options

{
  "plugins": [
    ["transform-runtime", {
      "helpers": true,
      "polyfill": true,
      "regenerator": true,
      "moduleName": "babel-runtime"
    }]
  ]
}

Via CLI

babel --plugins transform-runtime script.js

Via Node API

const babel = require("babel-core");

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

Architecture

The plugin operates through several key transformation phases:

  • Helper Aliasing: Replaces inline Babel helpers with imports from babel-runtime/helpers
  • Builtin Polyfilling: Transforms global built-in references to core-js imports
  • Regenerator Aliasing: Replaces regeneratorRuntime with babel-runtime/regenerator imports
  • Method Polyfilling: Transforms static method calls to use core-js equivalents
  • Iterator Handling: Special transformations for Symbol.iterator usage patterns

Capabilities

Main Plugin Export

The main export is a function that returns a Babel plugin object.

/**
 * babel-plugin-transform-runtime main export
 * @param {Object} babel - Babel instance with types utility
 * @param {Object} babel.types - Babel types utility object
 * @returns {Object} Babel plugin with pre hook and visitor
 */
function plugin({ types: t }) {
  return {
    pre(file) { /* ... */ },
    visitor: { /* ... */ }
  };
}

// Default export
export default plugin;

Plugin Configuration Options

Configure the plugin's transformation behavior through Babel options.

// Plugin options (passed via Babel configuration)
const pluginOptions = {
  /** Transform inline Babel helpers to imports from babel-runtime/helpers (default: true) */
  helpers: true,
  /** Transform built-ins to imports from babel-runtime/core-js (default: true) */
  polyfill: true,
  /** Transform generators/async functions to use babel-runtime/regenerator (default: true) */
  regenerator: true,
  /** Name of the runtime module to import from (default: "babel-runtime") */
  moduleName: "babel-runtime"
};

Definitions Export

Access to the builtin and method mapping definitions used by the plugin.

/**
 * Named export containing builtin and method mappings
 */
export { definitions };

// Definitions structure
const definitions = {
  /** Maps global built-in names to core-js module paths */
  builtins: {
    Symbol: "symbol",
    Promise: "promise",
    Map: "map",
    // ... more builtins
  },
  /** Maps static methods to core-js module paths organized by object type */
  methods: {
    Array: {
      from: "array/from",
      of: "array/of",
      // ... more methods
    },
    // ... more object types
  }
};

Usage:

import { definitions } from "babel-plugin-transform-runtime";

// Access builtin mappings
console.log(definitions.builtins.Promise); // "promise"

// Access method mappings
console.log(definitions.methods.Array.from); // "array/from"

Built-in Transformations

The plugin transforms the following built-in objects:

// Global built-ins transformed (when polyfill: true)
const builtins = {
  Symbol: "symbol",
  Promise: "promise", 
  Map: "map",
  WeakMap: "weak-map",
  Set: "set",
  WeakSet: "weak-set",
  Observable: "observable",
  setImmediate: "set-immediate",
  clearImmediate: "clear-immediate",
  asap: "asap"
  // Note: parseFloat and parseInt are temporarily disabled
};

Static Method Transformations

The plugin transforms static methods on these objects:

// Static methods transformed (when polyfill: true)
const methods = {
  Array: {
    copyWithin: "array/copy-within",
    entries: "array/entries",
    every: "array/every",
    fill: "array/fill",
    filter: "array/filter",
    find: "array/find",
    findIndex: "array/find-index",
    forEach: "array/for-each",
    from: "array/from",
    includes: "array/includes",
    indexOf: "array/index-of",
    join: "array/join",
    keys: "array/keys",
    lastIndexOf: "array/last-index-of",
    map: "array/map",
    of: "array/of",
    reduce: "array/reduce",
    reduceRight: "array/reduce-right",
    some: "array/some",
    sort: "array/sort",
    splice: "array/splice",
    values: "array/values",
    // Deprecated methods still supported:
    concat: "array/concat", // deprecated
    pop: "array/pop", // deprecated
    push: "array/push", // deprecated
    reverse: "array/reverse", // deprecated
    shift: "array/shift", // deprecated
    slice: "array/slice", // deprecated
    unshift: "array/unshift" // deprecated
  },
  Object: {
    assign: "object/assign",
    create: "object/create",
    defineProperties: "object/define-properties",
    defineProperty: "object/define-property",
    entries: "object/entries",
    freeze: "object/freeze",
    getOwnPropertyDescriptor: "object/get-own-property-descriptor",
    getOwnPropertyDescriptors: "object/get-own-property-descriptors",
    getOwnPropertyNames: "object/get-own-property-names",
    getOwnPropertySymbols: "object/get-own-property-symbols",
    getPrototypeOf: "object/get-prototype-of",
    is: "object/is",
    isExtensible: "object/is-extensible",
    isFrozen: "object/is-frozen",
    isSealed: "object/is-sealed",
    keys: "object/keys",
    preventExtensions: "object/prevent-extensions",
    seal: "object/seal",
    setPrototypeOf: "object/set-prototype-of",
    values: "object/values"
  },
  String: {
    at: "string/at",
    codePointAt: "string/code-point-at",
    endsWith: "string/ends-with",
    fromCodePoint: "string/from-code-point",
    includes: "string/includes",
    matchAll: "string/match-all",
    padEnd: "string/pad-end",
    padStart: "string/pad-start",
    raw: "string/raw",
    repeat: "string/repeat",
    startsWith: "string/starts-with",
    trim: "string/trim",
    trimEnd: "string/trim-end",
    trimLeft: "string/trim-left",
    trimRight: "string/trim-right",
    trimStart: "string/trim-start",
    // Deprecated methods still supported:
    padLeft: "string/pad-left", // deprecated
    padRight: "string/pad-right" // deprecated
  },
  Number: {
    EPSILON: "number/epsilon",
    isFinite: "number/is-finite",
    isInteger: "number/is-integer",
    isNaN: "number/is-nan",
    isSafeInteger: "number/is-safe-integer",
    MAX_SAFE_INTEGER: "number/max-safe-integer",
    MIN_SAFE_INTEGER: "number/min-safe-integer",
    parseFloat: "number/parse-float",
    parseInt: "number/parse-int"
  },
  Math: {
    acosh: "math/acosh",
    asinh: "math/asinh",
    atanh: "math/atanh",
    cbrt: "math/cbrt",
    clz32: "math/clz32",
    cosh: "math/cosh",
    expm1: "math/expm1",
    fround: "math/fround",
    hypot: "math/hypot",
    iaddh: "math/iaddh",
    imul: "math/imul",
    imulh: "math/imulh",
    isubh: "math/isubh",
    log10: "math/log10",
    log1p: "math/log1p",
    log2: "math/log2",
    sign: "math/sign",
    sinh: "math/sinh",
    tanh: "math/tanh",
    trunc: "math/trunc",
    umulh: "math/umulh"
  },
  Symbol: {
    for: "symbol/for",
    hasInstance: "symbol/has-instance",
    isConcatSpreadable: "symbol/is-concat-spreadable",
    iterator: "symbol/iterator",
    keyFor: "symbol/key-for",
    match: "symbol/match",
    replace: "symbol/replace",
    search: "symbol/search",
    species: "symbol/species",
    split: "symbol/split",
    toPrimitive: "symbol/to-primitive",
    toStringTag: "symbol/to-string-tag",
    unscopables: "symbol/unscopables"
  },
  Reflect: {
    apply: "reflect/apply",
    construct: "reflect/construct",
    defineProperty: "reflect/define-property",
    deleteProperty: "reflect/delete-property",
    get: "reflect/get",
    getOwnPropertyDescriptor: "reflect/get-own-property-descriptor",
    getPrototypeOf: "reflect/get-prototype-of",
    has: "reflect/has",
    isExtensible: "reflect/is-extensible",
    ownKeys: "reflect/own-keys",
    preventExtensions: "reflect/prevent-extensions",
    set: "reflect/set",
    setPrototypeOf: "reflect/set-prototype-of",
    // Metadata methods:
    defineMetadata: "reflect/define-metadata",
    deleteMetadata: "reflect/delete-metadata",
    getMetadata: "reflect/get-metadata",
    getMetadataKeys: "reflect/get-metadata-keys",
    getOwnMetadata: "reflect/get-own-metadata",
    getOwnMetadataKeys: "reflect/get-own-metadata-keys",
    hasMetadata: "reflect/has-metadata",
    hasOwnMetadata: "reflect/has-own-metadata",
    metadata: "reflect/metadata",
    // Deprecated methods still supported:
    enumerate: "reflect/enumerate" // deprecated
  },
  JSON: {
    stringify: "json/stringify"
  },
  RegExp: {
    escape: "regexp/escape" // deprecated
  },
  System: {
    global: "system/global"
  },
  Error: {
    isError: "error/is-error" // deprecated
  }
};

Transformation Examples

Helper Aliasing

Input:

class Person {}

Output (with helpers: true):

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Person = function Person() {
  (0, _classCallCheck3.default)(this, Person);
};

Built-in Polyfilling

Input:

var sym = Symbol();
var promise = new Promise();

Output (with polyfill: true):

var _symbol = require("babel-runtime/core-js/symbol");
var _symbol2 = _interopRequireDefault(_symbol);
var _promise = require("babel-runtime/core-js/promise");
var _promise2 = _interopRequireDefault(_promise);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var sym = (0, _symbol2.default)();
var promise = new _promise2.default();

Regenerator Aliasing

Input:

function* foo() {
  yield 42;
}

Output (with regenerator: true):

var _regenerator = require("babel-runtime/regenerator");
var _regenerator2 = _interopRequireDefault(_regenerator);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _marked = [foo].map(_regenerator2.default.mark);

function foo() {
  return _regenerator2.default.wrap(function foo$(_context) {
    while (1) switch (_context.prev = _context.next) {
      case 0:
      case "end":
        return _context.stop();
    }
  }, _marked[0], this);
}

Static Method Polyfilling

Input:

Array.from(iterable);
Object.assign(target, source);

Output (with polyfill: true):

var _from = require("babel-runtime/core-js/array/from");
var _from2 = _interopRequireDefault(_from);
var _assign = require("babel-runtime/core-js/object/assign");
var _assign2 = _interopRequireDefault(_assign);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

(0, _from2.default)(iterable);
(0, _assign2.default)(target, source);

Error Handling

The plugin handles various edge cases:

  • Scope conflicts: Checks for local bindings before transforming global references
  • Object.defineProperty optimization: Special handling when using string keys to avoid core-js overhead
  • Helper blacklist: Excludes interopRequireWildcard and interopRequireDefault from transformation
  • Iterator patterns: Special handling for Symbol.iterator in call expressions and binary expressions

Dependencies

  • babel-runtime (^6.22.0) - Required runtime dependency providing helpers and polyfills
  • Must be installed as a production dependency alongside the plugin

Special Transformations

Iterator Pattern Handling

The plugin handles special cases for Symbol.iterator:

// Input: arr[Symbol.iterator]()
// Output: _core.getIterator(arr)

// Input: Symbol.iterator in arr  
// Output: _core.isIterable(arr)

Object.defineProperty Optimization

The plugin avoids core-js overhead for Object.defineProperty with string keys:

// This will NOT be transformed (performance optimization):
Object.defineProperty(obj, "key", descriptor);

// This WILL be transformed:
Object.defineProperty(obj, dynamicKey, descriptor);

Helper Blacklist

Certain helpers are excluded from transformation:

  • interopRequireWildcard
  • interopRequireDefault

These remain as inline helpers to avoid circular dependencies.

docs

index.md

tile.json