Rollup plugin for shimming Node.js built-in modules in browser environments
npx @tessl/cli install tessl/npm-rollup-plugin-node-builtins@2.1.0Rollup 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.
npm install rollup-plugin-node-builtinsimport builtins from "rollup-plugin-node-builtins";For CommonJS:
const builtins = require("rollup-plugin-node-builtins");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
})
]
};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;
}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[];
}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;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 ':'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 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 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;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);
}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;
}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 mappingBrowser-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'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 constantsLimited 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;
}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;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;
};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 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;
};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 constantsMock 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 browserThe 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 availableSeveral 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 objectThe plugin resolves Node.js built-in module imports to browser-compatible implementations:
| Node.js Module | Implementation | Type |
|---|---|---|
events | src/es6/events.js | Full EventEmitter implementation |
util | src/es6/util.js | Complete utility functions |
sys | src/es6/util.js | Alias for util (deprecated) |
path | src/es6/path.js | POSIX path operations |
assert | src/es6/assert.js | All assertion functions |
url | src/es6/url.js | URL parsing and formatting |
querystring | src/es6/qs.js | Query string utilities |
punycode | src/es6/punycode.js | Punycode encoding/decoding |
http/https | src/es6/http.js | Browser-adapted HTTP client |
stream | src/es6/stream.js | Complete stream classes |
_stream_readable | src/es6/readable-stream/readable.js | Readable stream class |
_stream_writable | src/es6/readable-stream/writable.js | Writable stream class |
_stream_duplex | src/es6/readable-stream/duplex.js | Duplex stream class |
_stream_transform | src/es6/readable-stream/transform.js | Transform stream class |
_stream_passthrough | src/es6/readable-stream/passthrough.js | PassThrough stream class |
string_decoder | src/es6/string-decoder.js | String decoding utilities |
zlib | src/es6/zlib.js | Pure JS compression |
os | src/es6/os.js | Browser-adapted OS info |
vm | src/es6/vm.js | Limited code execution |
timers | src/es6/timers.js | Browser timer functions |
console | src/es6/console.js | Browser console object |
domain | src/es6/domain.js | Simplified error domains |
tty | src/es6/tty.js | Mock TTY functions |
constants | dist/constants.js | System constants |
process | process-es6 | External dependency |
buffer | buffer-es6 | External dependency |
crypto | crypto-browserify | Optional external |
fs | browserify-fs | Optional external |
| Mock modules | src/es6/empty.js | Empty objects |
// 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()]
};// 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");// 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"));