or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

babel-plugin-polyfill-corejs2

babel-plugin-polyfill-corejs2 is a Babel plugin that automatically injects polyfill imports for core-js@2 based on usage analysis and compilation targets. It analyzes your code to determine which core-js@2 polyfills are needed and automatically adds the appropriate imports, helping developers ensure their JavaScript code works across different browser environments while minimizing bundle size.

Package Information

  • Package Name: babel-plugin-polyfill-corejs2
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev babel-plugin-polyfill-corejs2

Core Imports

This is a Babel plugin, so it's not imported directly in code but configured in Babel configuration:

{
  "plugins": [["polyfill-corejs2", { "method": "usage-global" }]]
}

For programmatic usage:

const plugin = require("babel-plugin-polyfill-corejs2");
const { hasMinVersion } = require("babel-plugin-polyfill-corejs2");

ESM:

import plugin, { hasMinVersion } from "babel-plugin-polyfill-corejs2";

Basic Usage

Configure the plugin in your Babel configuration with one of three injection methods:

{
  "plugins": [
    ["polyfill-corejs2", { "method": "usage-global" }]
  ]
}

Usage Global - Analyzes code and injects global polyfills:

// Input code using ES6 features
const result = [1, 2, 3].includes(2);
const promise = Promise.resolve(42);

// Plugin automatically adds necessary imports:
// import "core-js/modules/es7.array.includes.js";
// import "core-js/modules/es6.promise.js";

Usage Pure - Injects pure polyfills that don't pollute global scope:

{
  "plugins": [
    ["polyfill-corejs2", { "method": "usage-pure" }]
  ]
}

Entry Global - Replaces core-js imports with specific polyfills:

{
  "plugins": [
    ["polyfill-corejs2", { "method": "entry-global" }]
  ]
}

Architecture

The plugin is built using @babel/helper-define-polyfill-provider and operates through several key components:

  • Provider System: Uses defineProvider from @babel/helper-define-polyfill-provider to create a standardized polyfill provider
  • Meta Resolver: Creates resolvers for global, static, and instance property polyfills using built-in definitions
  • Polyfill Resolution: Maps JavaScript features to core-js@2 polyfill modules via comprehensive lookup tables
  • Target Analysis: Uses browser/environment targets and platform detection to determine necessary polyfills
  • Code Analysis: Analyzes AST to detect polyfill-requiring language constructs and usage patterns
  • Import Injection: Adds appropriate core-js@2 imports based on method (usage-global, usage-pure, entry-global) and runtime context
  • Platform-Specific Handling: Adds web-specific polyfills and pure-only polyfills based on target environment

Capabilities

Plugin Function

Main Babel plugin function created using defineProvider from @babel/helper-define-polyfill-provider.

/**
 * Main Babel plugin export - a polyfill provider for core-js@2
 * Created using defineProvider with options for polyfill injection
 */
declare const plugin: (api: ProviderApi, options: ProviderOptions) => PolyfillProvider;
export default plugin;

interface ProviderOptions {
  /** Internal preset-env compatibility options */
  "#__secret_key__@babel/preset-env__compatibility"?: {
    entryInjectRegenerator: boolean;
    noRuntimeName: boolean;
  };
  /** Internal runtime compatibility options */
  "#__secret_key__@babel/runtime__compatibility"?: {
    useBabelRuntime: boolean;
    runtimeVersion: string;
    ext: string;
  };
}

interface PolyfillProvider {
  name: string;
  runtimeName: string | null;
  polyfills: Record<string, any>;
  entryGlobal(meta: any, utils: any, path: any): void;
  usageGlobal(meta: any, utils: any): void;
  usagePure(meta: any, utils: any, path: any): void;
  visitor?: any;
}

Polyfill Method Support

The plugin supports three distinct injection methods:

Usage Global Method: Analyzes code usage and injects global polyfills

  • Scans AST for polyfill-requiring constructs
  • Injects core-js/modules/ imports
  • Modifies global environment

Usage Pure Method: Injects pure polyfills without global pollution

  • Replaces usage with core-js/library/fn/ imports
  • Maintains original semantics without side effects
  • Ideal for library authors

Entry Global Method: Replaces core-js imports with specific modules

  • Transforms import "core-js" to specific polyfill imports
  • Based on target environment capabilities
  • Reduces bundle size by including only needed polyfills

Helper Functions

The plugin exports utility functions for version checking and compatibility.

/**
 * Checks if a minimum version requirement is satisfied by a runtime version
 * @param minVersion - Minimum required version string
 * @param runtimeVersion - Runtime version to check against
 * @returns true if version requirement is satisfied
 */
export function hasMinVersion(
  minVersion?: string | null,
  runtimeVersion?: string | number | null
): boolean;

Standard Babel Plugin Configuration

When used as a Babel plugin, it accepts standard method and target options:

interface BabelPluginOptions {
  /** 
   * Polyfill injection method:
   * - "usage-global": Analyze usage and inject global polyfills
   * - "usage-pure": Inject pure polyfills without global pollution  
   * - "entry-global": Replace core-js imports with specific polyfills
   */
  method: "usage-global" | "usage-pure" | "entry-global";
  
  /** Browser/environment targets for determining needed polyfills */
  targets?: Targets;
  
  /** Runtime version for @babel/runtime-corejs2 compatibility */
  version?: string;
}

Built-in Definitions

The plugin includes comprehensive polyfill mappings organized into three categories:

Built-in Objects - Global constructors and objects:

  • Typed arrays (DataView, Float32Array, Int8Array, etc.)
  • Collections (Map, Set, WeakMap, WeakSet)
  • Core objects (Promise, Symbol, RegExp)
  • Utility functions (setImmediate, clearImmediate, parseFloat, parseInt)

Static Properties - Static methods on built-in objects:

  • Array.from, Array.isArray, Array.of
  • Object.assign, Object.entries, Object.keys, etc.
  • Math.sign, Math.trunc, hyperbolic functions
  • Number.isFinite, Number.EPSILON, etc.
  • Reflect API methods
  • String.fromCodePoint, String.raw
  • Symbol static methods

Instance Properties - Prototype methods and properties:

  • Array methods (includes, find, flatMap, etc.)
  • String methods (startsWith, endsWith, padStart, etc.)
  • Function methods (bind, name)
  • Date methods (toISOString, toJSON)
  • RegExp methods (match, replace, search, split)

Common Polyfill Categories

ECMAScript 6+ Features

  • Promises: es6.promise with iterator dependencies
  • Symbols: es6.symbol with various symbol types
  • Collections: Map, Set, WeakMap, WeakSet with iterator support
  • Typed Arrays: All typed array constructors and methods
  • Object Methods: Object.assign, Object.is, Object.keys, etc.
  • Array Methods: Array.from, Array.of, iterator methods
  • String Methods: String.includes, String.startsWith, etc.
  • Math Methods: Math.sign, Math.trunc, hyperbolic functions
  • Number Methods: Number.isFinite, Number.EPSILON, etc.

ECMAScript 7+ Features

  • Array Methods: Array.prototype.includes, Array.prototype.flatMap
  • Object Methods: Object.entries, Object.values, Object.getOwnPropertyDescriptors
  • String Methods: String.prototype.padStart, String.prototype.padEnd
  • Promise Methods: Promise.prototype.finally

Web Platform Features

  • Timers: setImmediate, clearImmediate
  • DOM Iterables: Iterator support for DOM collections
  • Parse Functions: parseFloat, parseInt polyfills

Runtime Integration

Babel Runtime Support

When used with @babel/runtime-corejs2, the plugin automatically adjusts import paths:

// Standard usage-pure
import includes from "core-js/library/fn/array/includes";

// With @babel/runtime-corejs2  
import includes from "@babel/runtime-corejs2/core-js/array/includes";

Target-Aware Polyfills

The plugin respects Babel's targets configuration to include only necessary polyfills:

// For targets: { "chrome": "60" }
// Skips polyfills already supported in Chrome 60+

// For targets: { "ie": "11" }  
// Includes comprehensive polyfill set for IE11 compatibility

Error Handling

The plugin handles various edge cases gracefully:

  • Missing Polyfills: Silently skips unavailable polyfills (e.g., web.dom.iterable in Node.js)
  • Version Conflicts: Checks runtime version compatibility before injection
  • Platform Mismatches: Filters polyfills based on target environment
  • Import Conflicts: Avoids duplicate imports and handles existing core-js imports

Types

/** Browser/environment compilation targets from @babel/helper-define-polyfill-provider */
interface Targets {
  [environment: string]: string | number;
}

/** Provider API from @babel/helper-define-polyfill-provider */
interface ProviderApi {
  createMetaResolver(config: MetaResolverConfig): MetaResolver;
  targets: Targets;
  debug: (name: string | null) => void;
  shouldInjectPolyfill: (name: string) => boolean;
  method: "usage-global" | "usage-pure" | "entry-global";
  getUtils: (path: any) => ProviderUtils;
}

interface MetaResolverConfig {
  global: Record<string, PolyfillDescriptor<any>>;
  static: Record<string, Record<string, PolyfillDescriptor<any>>>;
  instance: Record<string, PolyfillDescriptor<any>>;
}

interface MetaResolver {
  (meta: any): ResolvedPolyfill | undefined;
}

interface ResolvedPolyfill {
  desc: PolyfillDescriptor<any>;
  name: string;
  kind: string;
}

interface PolyfillDescriptor<T> {
  name: string;
  pure: string | null;
  global: string[];
  meta: T | null;
}

interface ProviderUtils {
  injectGlobalImport: (source: string) => void;
  injectDefaultImport: (source: string, hint: string) => any;
}

/** Core-js@2 specific metadata */
interface CoreJS2Meta {
  minRuntimeVersion: string | null;
}