CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rollup-plugin-node-builtins

Rollup plugin for shimming Node.js built-in modules in 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

index.mddocs/

Rollup Plugin Node Builtins

Rollup Plugin Node Builtins is a Rollup plugin that provides browser-compatible polyfills for Node.js built-in modules. It enables Node.js code to run in browser environments by shimming all core Node.js modules with ES6-compatible implementations or external dependencies.

Package Information

  • Package Name: rollup-plugin-node-builtins
  • Package Type: npm
  • Language: JavaScript (ES6)
  • Installation: npm install rollup-plugin-node-builtins

Core Imports

import builtins from "rollup-plugin-node-builtins";

For CommonJS:

const builtins = require("rollup-plugin-node-builtins");

Basic Usage

import builtins from "rollup-plugin-node-builtins";

// Basic Rollup configuration
export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "iife"
  },
  plugins: [builtins()]
};

// With optional crypto and fs support
export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "iife"
  },
  plugins: [
    builtins({
      crypto: true,  // Enable crypto-browserify
      fs: true       // Enable browserify-fs
    })
  ]
};

Capabilities

Plugin Configuration

The main plugin function that creates a Rollup plugin for Node.js built-in module resolution.

/**
 * Creates a Rollup plugin for Node.js built-in module polyfills
 * @param {Object} [opts] - Configuration options
 * @param {boolean} [opts.crypto=false] - Enable crypto-browserify module
 * @param {boolean} [opts.fs=false] - Enable browserify-fs module
 * @returns {Object} Rollup plugin object with resolveId method
 */
function builtins(opts?: PluginOptions): RollupPlugin;

interface PluginOptions {
  crypto?: boolean;  // Enable crypto-browserify (default: false)
  fs?: boolean;      // Enable browserify-fs (default: false)
}

interface RollupPlugin {
  resolveId(importee: string): string | undefined;
}

Event System

Browser-compatible EventEmitter implementation that matches Node.js events API.

// Import from 'events' module
import EventEmitter from "events";
import { EventEmitter } from "events";

class EventEmitter {
  constructor();
  
  // Static properties
  static defaultMaxListeners: number;  // Default: 10
  static listenerCount(emitter: EventEmitter, type: string): number;
  
  // Instance methods
  setMaxListeners(n: number): EventEmitter;
  getMaxListeners(): number;
  emit(type: string, ...args: any[]): boolean;
  on(type: string, listener: Function): EventEmitter;
  addListener(type: string, listener: Function): EventEmitter;
  once(type: string, listener: Function): EventEmitter;
  prependListener(type: string, listener: Function): EventEmitter;
  prependOnceListener(type: string, listener: Function): EventEmitter;
  removeListener(type: string, listener: Function): EventEmitter;
  removeAllListeners(type?: string): EventEmitter;
  listeners(type: string): Function[];
  listenerCount(type: string): number;
  eventNames(): string[];
}

Utility Functions

Core utility functions for formatting, inspection, and type checking.

// Import from 'util' module
import { format, inspect, inherits } from "util";

// 'sys' module is an alias for 'util' (deprecated Node.js alias)
import { format, inspect, inherits } from "sys";

// String formatting with placeholders
function format(f: string, ...args: any[]): string;

// Object inspection and formatting
function inspect(obj: any, opts?: object): string;

// Function deprecation wrapper
function deprecate(fn: Function, msg: string): Function;

// Debug logger creation
function debuglog(set: string): Function;

// Prototype inheritance setup
function inherits(constructor: Function, superConstructor: Function): void;

// Shallow object extension
function _extend(origin: object, add: object): object;

// Console logging
function log(...args: any[]): void;

// Type checking functions
function isArray(ar: any): boolean;
function isBoolean(arg: any): boolean;
function isNull(arg: any): boolean;
function isNullOrUndefined(arg: any): boolean;
function isNumber(arg: any): boolean;
function isString(arg: any): boolean;
function isSymbol(arg: any): boolean;
function isUndefined(arg: any): boolean;
function isRegExp(re: any): boolean;
function isObject(arg: any): boolean;
function isDate(d: any): boolean;
function isError(e: any): boolean;
function isFunction(arg: any): boolean;
function isPrimitive(arg: any): boolean;
function isBuffer(maybeBuf: any): boolean;

Path Utilities

Cross-platform path manipulation functions with POSIX-style behavior in browsers.

// Import from 'path' module
import { resolve, join, dirname, basename, extname } from "path";

// Path resolution and normalization
function resolve(...paths: string[]): string;
function normalize(path: string): string;
function isAbsolute(path: string): boolean;
function join(...paths: string[]): string;
function relative(from: string, to: string): string;

// Path component extraction
function dirname(path: string): string;
function basename(path: string, ext?: string): string;
function extname(path: string): string;

// Path constants
const sep: string;        // Path separator '/'
const delimiter: string;  // Path delimiter ':'

Assertion Testing

Comprehensive assertion functions for testing and validation.

// Import from 'assert' module
import assert, { equal, strictEqual, deepEqual } from "assert";

// Basic assertion
function assert(value: any, message?: string): void;
function ok(value: any, message?: string): void;

// Equality assertions
function equal(actual: any, expected: any, message?: string): void;
function notEqual(actual: any, expected: any, message?: string): void;
function strictEqual(actual: any, expected: any, message?: string): void;
function notStrictEqual(actual: any, expected: any, message?: string): void;

// Deep equality assertions
function deepEqual(actual: any, expected: any, message?: string): void;
function notDeepEqual(actual: any, expected: any, message?: string): void;
function deepStrictEqual(actual: any, expected: any, message?: string): void;
function notDeepStrictEqual(actual: any, expected: any, message?: string): void;

// Exception testing
function throws(block: Function, error?: Function | RegExp, message?: string): void;
function doesNotThrow(block: Function, error?: Function | RegExp, message?: string): void;

// Error checking and manual failure
function ifError(err: any): void;
function fail(actual?: any, expected?: any, message?: string, operator?: string, stackStartFunction?: Function): void;

// Error class
class AssertionError extends Error {
  name: string;
  message: string;
  actual: any;
  expected: any;
  operator: string;
  constructor(options: object);
}

URL Utilities

URL parsing, formatting, and resolution functions.

// Import from 'url' module
import { parse, format, resolve } from "url";

// URL parsing and formatting
function parse(url: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): UrlObject;
function format(urlObject: UrlObject): string;
function resolve(from: string, to: string): string;
function resolveObject(from: UrlObject, relative: UrlObject): UrlObject;

// URL object type
interface UrlObject {
  protocol?: string;
  slashes?: boolean;
  auth?: string;
  host?: string;
  port?: string;
  hostname?: string;
  hash?: string;
  search?: string;
  query?: string | object;
  pathname?: string;
  path?: string;
  href?: string;
}

// URL class
class Url {
  constructor();
  parse(url: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): void;
  format(): string;
  resolve(relative: string): string;
  resolveObject(relative: UrlObject): UrlObject;
  parseHost(): void;
}

Query String Utilities

Query string encoding and decoding functions.

// Import from 'querystring' module
import { stringify, parse, encode, decode } from "querystring";

// Query string serialization
function stringify(obj: object, sep?: string, eq?: string, name?: string): string;
function encode(obj: object, sep?: string, eq?: string, name?: string): string;

// Query string parsing  
function parse(qs: string, sep?: string, eq?: string, options?: object): object;
function decode(qs: string, sep?: string, eq?: string, options?: object): object;

Stream System

Complete stream implementation with Readable, Writable, Duplex, Transform, and PassThrough streams.

// Import from 'stream' module
import { Readable, Writable, Duplex, Transform, PassThrough } from "stream";

// Individual stream modules are also available as separate imports
import Readable from "stream/_stream_readable";
import Writable from "stream/_stream_writable";  
import Duplex from "stream/_stream_duplex";
import Transform from "stream/_stream_transform";
import PassThrough from "stream/_stream_passthrough";

// Base stream class
class Stream extends EventEmitter {
  constructor();
}

// Readable stream
class Readable extends Stream {
  constructor(options?: object);
  read(size?: number): any;
  push(chunk: any, encoding?: string): boolean;
  unshift(chunk: any): void;
  pipe(destination: Writable, options?: object): Writable;
  unpipe(destination?: Writable): Readable;
  pause(): Readable;
  resume(): Readable;
  isPaused(): boolean;
  setEncoding(encoding: string): Readable;
  wrap(stream: Stream): Readable;
}

// Writable stream
class Writable extends Stream {
  constructor(options?: object);
  write(chunk: any, encoding?: string, callback?: Function): boolean;
  end(chunk?: any, encoding?: string, callback?: Function): void;
  cork(): void;
  uncork(): void;
  setDefaultEncoding(encoding: string): Writable;
}

// Duplex stream (readable and writable)
class Duplex extends Readable {
  constructor(options?: object);
  // Includes all Readable and Writable methods
}

// Transform stream
class Transform extends Duplex {
  constructor(options?: object);
  _transform(chunk: any, encoding: string, callback: Function): void;
  push(chunk: any, encoding?: string): boolean;
}

// PassThrough stream (transform that passes data unchanged)
class PassThrough extends Transform {
  constructor(options?: object);
}

String Decoder

Buffer to string decoding with proper handling of multi-byte characters.

// Import from 'string_decoder' module
import { StringDecoder } from "string_decoder";

class StringDecoder {
  constructor(encoding?: string);
  write(buffer: Buffer): string;
  end(buffer?: Buffer): string;
}

HTTP Client

Browser-adapted HTTP client functionality for making requests.

// Import from 'http' module
import { request, get, Agent, METHODS, STATUS_CODES } from "http";

// HTTP request functions
function request(opts: object | string, cb?: Function): ClientRequest;
function get(opts: object | string, cb?: Function): ClientRequest;

// HTTP agent for connection pooling
class Agent {
  constructor(options?: object);
}

// HTTP constants
const METHODS: string[];           // Array of HTTP method names
const STATUS_CODES: object;        // Status code to message mapping

Operating System Utilities

Browser-adapted OS information functions.

// Import from 'os' module
import { platform, arch, endianness, hostname, type, release } from "os";

// System information
function endianness(): string;     // CPU endianness
function hostname(): string;       // System hostname
function loadavg(): number[];      // Load average (returns [0, 0, 0] in browser)
function uptime(): number;         // System uptime in seconds
function freemem(): number;        // Free memory in bytes
function totalmem(): number;       // Total memory in bytes
function cpus(): object[];         // CPU information
function type(): string;           // Operating system name
function release(): string;        // Operating system release
function platform(): string;       // Operating system platform
function arch(): string;           // CPU architecture
function tmpdir(): string;         // Temporary directory path
function tmpDir(): string;         // Alias for tmpdir()
function networkInterfaces(): object;       // Network interfaces
function getNetworkInterfaces(): object;    // Alias for networkInterfaces()

// Constants
const EOL: string;                // End of line character '\n'

Compression (Zlib)

Pure JavaScript implementation of zlib compression algorithms.

// Import from 'zlib' module
import { createGzip, createGunzip, gzip, gunzip, deflate, inflate } from "zlib";

// Stream creation functions
function createDeflate(options?: object): Deflate;
function createInflate(options?: object): Inflate;
function createDeflateRaw(options?: object): DeflateRaw;
function createInflateRaw(options?: object): InflateRaw;
function createGzip(options?: object): Gzip;
function createGunzip(options?: object): Gunzip;
function createUnzip(options?: object): Unzip;

// Compression classes (extend Transform stream)
class Deflate extends Transform {}
class Inflate extends Transform {}
class Gzip extends Transform {}
class Gunzip extends Transform {}
class DeflateRaw extends Transform {}
class InflateRaw extends Transform {}
class Unzip extends Transform {}
class Zlib extends Transform {}

// Synchronous compression functions
function deflate(buffer: Buffer, options?: object, callback?: Function): Buffer;
function deflateSync(buffer: Buffer, options?: object): Buffer;
function inflate(buffer: Buffer, options?: object, callback?: Function): Buffer;
function inflateSync(buffer: Buffer, options?: object): Buffer;
function gzip(buffer: Buffer, options?: object, callback?: Function): Buffer;
function gzipSync(buffer: Buffer, options?: object): Buffer;
function gunzip(buffer: Buffer, options?: object, callback?: Function): Buffer;  
function gunzipSync(buffer: Buffer, options?: object): Buffer;
function deflateRaw(buffer: Buffer, options?: object, callback?: Function): Buffer;
function deflateRawSync(buffer: Buffer, options?: object): Buffer;
function inflateRaw(buffer: Buffer, options?: object, callback?: Function): Buffer;
function inflateRawSync(buffer: Buffer, options?: object): Buffer;
function unzip(buffer: Buffer, options?: object, callback?: Function): Buffer;
function unzipSync(buffer: Buffer, options?: object): Buffer;

// Constants
const codes: object;              // Z_* compression constants

Virtual Machine

Limited JavaScript code execution context functionality.

// Import from 'vm' module
import { createContext, runInContext, runInThisContext, runInNewContext, createScript, isContext } from "vm";

// Context creation and execution
function createContext(sandbox?: object): object;
function runInContext(code: string, context: object, options?: object): any;
function runInThisContext(code: string, options?: object): any;
function runInNewContext(code: string, sandbox?: object, options?: object): any;
function createScript(code: string, options?: object): Script;
function isContext(context: object): boolean;

// Script class
class Script {
  constructor(code: string, options?: object);
  runInContext(context: object, options?: object): any;
  runInThisContext(options?: object): any;
  runInNewContext(sandbox?: object, options?: object): any;
}

Timer Functions

Browser-adapted timer functions using native browser APIs.

// Import from 'timers' module
import { setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate } from "timers";

// Timer functions
function setTimeout(callback: Function, delay: number, ...args: any[]): object;
function clearTimeout(timeoutObject: object): void;
function setInterval(callback: Function, delay: number, ...args: any[]): object;
function clearInterval(intervalObject: object): void;
function setImmediate(callback: Function, ...args: any[]): object;
function clearImmediate(immediateObject: object): void;

// Internal timer functions
function enroll(item: object, msecs: number): void;
function unenroll(item: object): void;
function active(item: object): void;
function _unrefActive(item: object): void;

Console Functions

Browser-adapted console logging functions.

// Import from 'console' module - provides console object
import console from "console";

// Console methods
const console: {
  log(...args: any[]): void;
  info(...args: any[]): void;
  warn(...args: any[]): void;
  error(...args: any[]): void;
  dir(obj: any): void;
  assert(value: any, message?: string): void;
  time(label: string): void;
  timeEnd(label: string): void;
  trace(): void;
};

Domain Module

Simplified error handling domain implementation.

// Import from 'domain' module
import { createDomain, create, Domain } from "domain";

// Domain creation
function createDomain(): Domain;
function create(): Domain;

// Domain class
class Domain extends EventEmitter {
  constructor();
  add(emitter: EventEmitter): void;
  remove(emitter: EventEmitter): void;
  bind(fn: Function): Function;
  intercept(fn: Function): Function;
  run(fn: Function): void;
  dispose(): void;
  enter(): void;  // No-op in browser
  exit(): void;   // No-op in browser
}

Punycode Utilities

Punycode encoding and decoding for internationalized domain names.

// Import from 'punycode' module
import { decode, encode, toUnicode, toASCII, version, ucs2 } from "punycode";

// Punycode functions
function decode(input: string): string;
function encode(input: string): string;
function toUnicode(input: string): string;
function toASCII(input: string): string;

// Constants and utilities
const version: string;            // Version '1.4.1'
const ucs2: {
  decode(string: string): number[];
  encode(codePoints: number[]): string;
};

System Constants

Comprehensive system constants for errors, signals, file system, and SSL.

// Import from 'constants' module
import { 
  E2BIG, EACCES, EADDRINUSE, 
  SIGHUP, SIGINT, SIGQUIT,
  O_RDONLY, O_WRONLY, S_IRUSR,
  SSL_OP_ALL, TLS1_VERSION,
  PRIORITY_LOW, PRIORITY_HIGH 
} from "constants";

// Error constants
const E2BIG: number;
const EACCES: number;
const EADDRINUSE: number;
// ... many more error constants

// Signal constants  
const SIGHUP: number;
const SIGINT: number;
const SIGQUIT: number;
// ... many more signal constants

// File system constants
const O_RDONLY: number;
const O_WRONLY: number;
const S_IRUSR: number;
// ... many more file system constants

// SSL constants
const SSL_OP_ALL: number;
const TLS1_VERSION: number;
// ... many more SSL constants

// Process priority constants
const PRIORITY_LOW: number;
const PRIORITY_HIGH: number;
// ... additional priority constants

TTY Module

Mock TTY functionality for browser environments.

// Import from 'tty' module  
import { isatty, ReadStream, WriteStream } from "tty";

// TTY functions (browser-adapted)
function isatty(): boolean;       // Always returns false in browser
function ReadStream(): void;      // Throws error - not supported in browser
function WriteStream(): void;     // Throws error - not supported in browser

Optional External Modules

The plugin can optionally enable crypto and fs modules through external packages.

// Available when opts.crypto = true
// Uses crypto-browserify package
import { createHash, createHmac, randomBytes } from "crypto";
// Full crypto-browserify API available

// Available when opts.fs = true  
// Uses browserify-fs package
import { readFile, writeFile, readFileSync, writeFileSync } from "fs";
// Full browserify-fs API available

Mock Modules

Several Node.js modules return empty objects as they have no browser equivalent.

// These modules return empty objects {}
import dns from "dns";           // Empty object
import dgram from "dgram";       // Empty object  
import child_process from "child_process";  // Empty object
import cluster from "cluster";   // Empty object
import module from "module";     // Empty object
import net from "net";           // Empty object
import readline from "readline"; // Empty object
import repl from "repl";         // Empty object
import tls from "tls";           // Empty object

Module Resolution Map

The plugin resolves Node.js built-in module imports to browser-compatible implementations:

Node.js ModuleImplementationType
eventssrc/es6/events.jsFull EventEmitter implementation
utilsrc/es6/util.jsComplete utility functions
syssrc/es6/util.jsAlias for util (deprecated)
pathsrc/es6/path.jsPOSIX path operations
assertsrc/es6/assert.jsAll assertion functions
urlsrc/es6/url.jsURL parsing and formatting
querystringsrc/es6/qs.jsQuery string utilities
punycodesrc/es6/punycode.jsPunycode encoding/decoding
http/httpssrc/es6/http.jsBrowser-adapted HTTP client
streamsrc/es6/stream.jsComplete stream classes
_stream_readablesrc/es6/readable-stream/readable.jsReadable stream class
_stream_writablesrc/es6/readable-stream/writable.jsWritable stream class
_stream_duplexsrc/es6/readable-stream/duplex.jsDuplex stream class
_stream_transformsrc/es6/readable-stream/transform.jsTransform stream class
_stream_passthroughsrc/es6/readable-stream/passthrough.jsPassThrough stream class
string_decodersrc/es6/string-decoder.jsString decoding utilities
zlibsrc/es6/zlib.jsPure JS compression
ossrc/es6/os.jsBrowser-adapted OS info
vmsrc/es6/vm.jsLimited code execution
timerssrc/es6/timers.jsBrowser timer functions
consolesrc/es6/console.jsBrowser console object
domainsrc/es6/domain.jsSimplified error domains
ttysrc/es6/tty.jsMock TTY functions
constantsdist/constants.jsSystem constants
processprocess-es6External dependency
bufferbuffer-es6External dependency
cryptocrypto-browserifyOptional external
fsbrowserify-fsOptional external
Mock modulessrc/es6/empty.jsEmpty objects

Usage Examples

Basic Plugin Usage

// rollup.config.js
import builtins from "rollup-plugin-node-builtins";

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",  
    format: "iife"
  },
  plugins: [builtins()]
};

Using Node.js Modules in Browser Code

// Your application code can now use Node.js built-ins
import EventEmitter from "events";
import { format } from "util";
import { join } from "path";
import { parse } from "url";

// Create event emitter
const emitter = new EventEmitter();
emitter.on("data", (data) => {
  console.log(format("Received: %s", data));
});

// Use path utilities
const filePath = join("/users", "documents", "file.txt");

// Parse URLs
const parsed = parse("https://example.com/path?query=value");

Enabling Optional Modules

// rollup.config.js with crypto and fs support
import builtins from "rollup-plugin-node-builtins";

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "iife"
  },
  plugins: [
    builtins({
      crypto: true,  // Enables crypto-browserify
      fs: true       // Enables browserify-fs
    })
  ]
};

// Now you can use crypto and fs in your code
import { createHash } from "crypto";
import { readFile } from "fs";

const hash = createHash("sha256");
hash.update("hello world");
console.log(hash.digest("hex"));

docs

index.md

tile.json