CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vite-plugin-node-polyfills

A Vite plugin to polyfill Node's Core Modules for browser environments.

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

Vite Plugin Node Polyfills

A Vite plugin to polyfill Node's Core Modules for browser environments. This plugin enables Node.js packages to run in browsers by providing polyfills for all Node.js built-in modules, with support for the modern node: protocol imports and flexible configuration options.

Package Information

  • Package Name: vite-plugin-node-polyfills
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev vite-plugin-node-polyfills

Core Imports

import { nodePolyfills } from "vite-plugin-node-polyfills";

For CommonJS:

const { nodePolyfills } = require("vite-plugin-node-polyfills");

For shims (when using specific polyfills directly):

import "vite-plugin-node-polyfills/shims/buffer";
import "vite-plugin-node-polyfills/shims/global";
import "vite-plugin-node-polyfills/shims/process";

Basic Usage

import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";

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

With configuration:

import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";

export default defineConfig({
  plugins: [
    nodePolyfills({
      // Include specific modules only
      include: ["path", "fs"],
      // Exclude specific modules
      exclude: ["http"],
      // Configure global polyfills
      globals: {
        Buffer: true,
        global: "dev", // Only in development
        process: false, // Disable process polyfill
      },
      // Override default polyfills
      overrides: {
        fs: "memfs", // Use memfs instead of default fs polyfill
      },
      // Enable node: protocol polyfills
      protocolImports: true,
    }),
  ],
});

Architecture

The plugin works by:

  1. Module Resolution: Intercepts imports of Node.js core modules and redirects them to browser-compatible polyfills
  2. Global Injection: Optionally injects global variables (Buffer, global, process) into the browser environment
  3. Protocol Support: Handles both traditional imports (import "fs") and modern protocol imports (import "node:fs")
  4. Build Integration: Configures Vite's build pipeline to include polyfills and handle circular dependencies
  5. Development Support: Provides banner injection for isolated scripts (like Vue SFCs) in development mode

Capabilities

Main Plugin Function

Creates a Vite plugin instance with Node.js polyfill support.

/**
 * Returns a Vite plugin to polyfill Node's Core Modules for browser environments.
 * Supports node: protocol imports and provides flexible configuration options.
 * @param options - Configuration options for the plugin
 * @returns Vite Plugin object
 */
function nodePolyfills(options?: PolyfillOptions): Plugin;

interface PolyfillOptions {
  /** Specific modules to include. If empty, includes all modules */
  include?: ModuleNameWithoutNodePrefix[];
  /** Specific modules to exclude from polyfilling */
  exclude?: ModuleNameWithoutNodePrefix[];
  /** Configuration for global polyfills */
  globals?: {
    Buffer?: BooleanOrBuildTarget;
    global?: BooleanOrBuildTarget;
    process?: BooleanOrBuildTarget;
  };
  /** Alternative modules to use in place of default polyfills */
  overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string };
  /** Whether the Node protocol version should be polyfilled too (default: true) */
  protocolImports?: boolean;
}

type BooleanOrBuildTarget = boolean | BuildTarget;
type BuildTarget = "build" | "dev";
type ModuleName = keyof typeof stdLibBrowser;
type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never;

Usage Examples:

// Include only specific polyfills
nodePolyfills({
  include: ["fs", "path", "crypto"],
})

// Exclude specific polyfills
nodePolyfills({
  exclude: ["http", "https", "net"],
})

// Configure globals for different build modes
nodePolyfills({
  globals: {
    Buffer: "build", // Only in production builds
    global: true,    // Always available
    process: "dev",  // Only in development
  },
})

// Override default polyfills with custom implementations
nodePolyfills({
  overrides: {
    fs: "memfs",           // Use memfs for filesystem operations
    crypto: "crypto-js",   // Use crypto-js for cryptographic functions
  },
})

// Disable node: protocol imports
nodePolyfills({
  protocolImports: false,
})

Shim Modules

Direct access to specific polyfills for manual integration.

// Buffer shim exports
export {
  Blob,
  BlobOptions,
  Buffer,
  File,
  FileOptions,
  INSPECT_MAX_BYTES,
  SlowBuffer,
  TranscodeEncoding,
  atob,
  btoa,
  constants,
  isAscii,
  isUtf8,
  kMaxLength,
  kStringMaxLength,
  resolveObjectURL,
  transcode,
} from "vite-plugin-node-polyfills/shims/buffer";

// Global shim export
export { global } from "vite-plugin-node-polyfills/shims/global";

// Process shim export
export { process } from "vite-plugin-node-polyfills/shims/process";

Usage Examples:

// Direct buffer import
import { Buffer } from "vite-plugin-node-polyfills/shims/buffer";

// Direct global import
import { global } from "vite-plugin-node-polyfills/shims/global";

// Direct process import
import { process } from "vite-plugin-node-polyfills/shims/process";

Supported Node.js Core Modules

The plugin provides polyfills for all Node.js core modules:

Stream Modules:

  • _stream_duplex, _stream_passthrough, _stream_readable, _stream_transform, _stream_writable

Core Modules:

  • assert, buffer, child_process, cluster, console, constants, crypto
  • dgram, dns, domain, events, fs, http, http2, https
  • module, net, os, path, process, punycode, querystring
  • readline, repl, stream, string_decoder, sys, timers, timers/promises
  • tls, tty, url, util, vm, zlib

When protocolImports is enabled (default), also supports node: prefixed imports for all modules (e.g., node:fs, node:path, node:crypto).

Types

type BuildTarget = "build" | "dev";

type BooleanOrBuildTarget = boolean | BuildTarget;

type ModuleName = keyof typeof stdLibBrowser;

type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never;

interface PolyfillOptions {
  include?: ModuleNameWithoutNodePrefix[];
  exclude?: ModuleNameWithoutNodePrefix[];
  globals?: {
    Buffer?: BooleanOrBuildTarget;
    global?: BooleanOrBuildTarget;
    process?: BooleanOrBuildTarget;
  };
  overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string };
  protocolImports?: boolean;
}

interface PolyfillOptionsResolved {
  include: ModuleNameWithoutNodePrefix[];
  exclude: ModuleNameWithoutNodePrefix[];
  globals: {
    Buffer: BooleanOrBuildTarget;
    global: BooleanOrBuildTarget;
    process: BooleanOrBuildTarget;
  };
  overrides: { [Key in ModuleNameWithoutNodePrefix]?: string };
  protocolImports: boolean;
}

Error Handling

The plugin handles common polyfill-related issues:

  • Circular Dependencies: Automatically suppresses circular dependency warnings from Node.js polyfills
  • Missing Modules: Gracefully handles cases where polyfills are not available for specific modules
  • Build Mode Detection: Correctly applies different polyfill strategies for development vs production builds
  • Protocol Import Resolution: Properly resolves both traditional and node: protocol imports
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/vite-plugin-node-polyfills@0.24.x
Publish Source
CLI
Badge
tessl/npm-vite-plugin-node-polyfills badge