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.
npm install --save-dev babel-plugin-polyfill-corejs2This 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";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" }]
]
}The plugin is built using @babel/helper-define-polyfill-provider and operates through several key components:
defineProvider from @babel/helper-define-polyfill-provider to create a standardized polyfill providerusage-global, usage-pure, entry-global) and runtime contextMain 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;
}The plugin supports three distinct injection methods:
Usage Global Method: Analyzes code usage and injects global polyfills
core-js/modules/ importsUsage Pure Method: Injects pure polyfills without global pollution
core-js/library/fn/ importsEntry Global Method: Replaces core-js imports with specific modules
import "core-js" to specific polyfill importsThe 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;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;
}The plugin includes comprehensive polyfill mappings organized into three categories:
Built-in Objects - Global constructors and objects:
DataView, Float32Array, Int8Array, etc.)Map, Set, WeakMap, WeakSet)Promise, Symbol, RegExp)setImmediate, clearImmediate, parseFloat, parseInt)Static Properties - Static methods on built-in objects:
Array.from, Array.isArray, Array.ofObject.assign, Object.entries, Object.keys, etc.Math.sign, Math.trunc, hyperbolic functionsNumber.isFinite, Number.EPSILON, etc.Reflect API methodsString.fromCodePoint, String.rawSymbol static methodsInstance Properties - Prototype methods and properties:
includes, find, flatMap, etc.)startsWith, endsWith, padStart, etc.)bind, name)toISOString, toJSON)match, replace, search, split)es6.promise with iterator dependencieses6.symbol with various symbol typesMap, Set, WeakMap, WeakSet with iterator supportObject.assign, Object.is, Object.keys, etc.Array.from, Array.of, iterator methodsString.includes, String.startsWith, etc.Math.sign, Math.trunc, hyperbolic functionsNumber.isFinite, Number.EPSILON, etc.Array.prototype.includes, Array.prototype.flatMapObject.entries, Object.values, Object.getOwnPropertyDescriptorsString.prototype.padStart, String.prototype.padEndPromise.prototype.finallysetImmediate, clearImmediateparseFloat, parseInt polyfillsWhen 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";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 compatibilityThe plugin handles various edge cases gracefully:
web.dom.iterable in Node.js)/** 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;
}