Polyfill Plugin

TIP

Normally, we don't need to inject polyfill for npm packages, this step should be done on the web application framework side, but in some scenarios we need to inject polyfill in order to make our library run directly in low version browsers.

Note that this plugin does not transform your code syntax, it only injects polyfill for unsupported functions used in your code, importing them as normal functions instead of polluting the global. You need to install the core-js-pure dependency.

Quick start

Install

npm
yarn
pnpm
bun
npm add @modern-js/plugin-module-polyfill -D

Register

In Modern.js Module, you can register plugins in the following way:

import { moduleTools, defineConfig } from '@modern-js/module-tools';
import { modulePluginPolyfill } from '@modern-js/plugin-module-polyfill';

export default defineConfig({
  plugins: [moduleTools(), modulePluginPolyfill()],
});

You can also configure registration via hooks, for example, if you have multiple build configurations at the same time and only need to inject the polyfill when bundle:

import { moduleTools, defineConfig } from '@modern-js/module-tools';
import { getPolyfillHook } from '@modern-js/plugin-module-polyfill';

const polyfillHook = getPolyfillHook();

export default defineConfig({
  plugins: [moduleTools()],
  buildConfig: [
    {
      buildType: 'bundle',
      hooks: [polyfillHook],
    },
    {
      buildType: 'bundleless',
    },
  ],
});

Config

  • Type
type options = {
  targets?: Record<string, string> | string;
};

targets

See Babel target.

This is a example.

import { moduleTools, defineConfig } from '@modern-js/module-tools';
import { modulePluginPolyfill } from '@modern-js/plugin-module-polyfill';

export default defineConfig({
  plugins: [
    moduleTools(),
    modulePluginPolyfill({
      targets: '> 0.25%, not dead',
    }),
  ],
});