Node Polyfill 插件

Node Polyfill 介绍

通常情况下,我们不会在浏览器端使用 Node 模块。但在当前代码需要同时在 Node 端和浏览器端运行时,用到一些 Node 模块是有可能的。Node Polyfill 为这些 Node 模块提供了浏览器版本的 polyfills。

通过使用 Node Polyfill 插件,会自动注入 Node 核心模块在浏览器端的 polyfills,让你可以在浏览器端放心使用这些模块。

快速开始

在 Modern.js 框架中使用

Modern.js 框架默认集成了 Builder 的 Node Polyfill 插件,因此,你不需要手动安装和注册插件,只需要将 output.disableNodePolyfill 设置为 false 即可:

export default defineConfig({
  output: {
    disableNodePolyfill: false,
  },
});

通过 Node API 使用

如果你直接使用了 Builder 的 Node API,那么需要手动安装和注册 Node Polyfill 插件。

安装插件

你可以通过如下的命令安装插件:

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

注册插件

通过 addPlugins 方法来注册 Node Polyfill 插件:

import { builderPluginNodePolyfill } from '@modern-js/builder-plugin-node-polyfill';

// 往 builder 实例上添加插件
builder.addPlugins([builderPluginNodePolyfill()]);

Node Polyfills

Globals

  • Buffer
  • process

当你在代码中使用以上全局变量时,对应 polyfill 会被自动注入。

const bufferData = Buffer.from('xxxx');

Modules

  • assert
  • buffer
  • console
  • constants
  • crypto
  • domain
  • events
  • http
  • https
  • os
  • path
  • punycode
  • process
  • querystring
  • stream
  • _stream_duplex
  • _stream_passthrough
  • _stream_readable
  • _stream_transform
  • _stream_writable
  • string_decoder
  • sys
  • timers
  • tty
  • url
  • util
  • vm
  • zlib

当你通过 requireimport 等语法在代码中引用以上模块时,对应 polyfill 会被注入。

import { Buffer } from 'buffer';

const bufferData = Buffer.from('xxxx');

Fallbacks

  • child_process
  • cluster
  • dgram
  • dns
  • fs
  • module
  • net
  • readline
  • repl
  • tls

目前浏览器端没有以上模块的 polyfill,因此当你引用以上模块时,会自动 fallback 为一个空对象。

import fs from 'fs';

console.log(fs); // -> {}