• Stars
    star
    185
  • Rank 208,271 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Node standard library for browser.

node-stdlib-browser

Build Status

Node standard library for browser.

Features:

  • Based on node-libs-browser for Webpack
  • Maintained with newer versions and modern implementations
  • Works with Webpack, Rollup, Vite, esbuild and Browserify, but should also work with other bundlers
  • Exports implementation with node: protocol which allows for builtin modules to be referenced by valid absolute URL strings

Check example to see how modules work in browser environment.

Install

npm install node-stdlib-browser --save-dev

Usage

Webpack

Show me

As of Webpack 5, aliases and globals provider need to be explicitly configured. If you want to handle node: protocol imports, you need to provide helper plugin.

// webpack.config.js
const stdLibBrowser = require('node-stdlib-browser');
const {
	NodeProtocolUrlPlugin
} = require('node-stdlib-browser/helpers/webpack/plugin');
const webpack = require('webpack');

module.exports = {
	// ...
	resolve: {
		alias: stdLibBrowser
	},
	plugins: [
		new NodeProtocolUrlPlugin(),
		new webpack.ProvidePlugin({
			process: stdLibBrowser.process,
			Buffer: [stdLibBrowser.buffer, 'Buffer']
		})
	]
};

If you’re using ESM config, additional configuration is needed to handle unspecified extensions:

// webpack.config.js
module.exports = {
	// ...
	module: {
		rules: [
			{
				test: /\.m?js$/,
				resolve: {
					fullySpecified: false
				}
			}
		]
	}
};

Rollup

Show me

Since many packages expose only CommonJS implementation, you need to apply plugins to handle CommonJS exports. Those packages could have dependencies installed with npm so they need to be properly resolved (taking into account browser-specific implementations).

Some dependencies can have circular dependencies and Rollup will warn you about that. You can ignore these warnings with helper function (reference).

// rollup.config.js
const stdLibBrowser = require('node-stdlib-browser');
const {
	handleCircularDependancyWarning
} = require('node-stdlib-browser/helpers/rollup/plugin');
const { default: resolve } = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const json = require('@rollup/plugin-json');
const alias = require('@rollup/plugin-alias');
const inject = require('@rollup/plugin-inject');

module.exports = {
	// ...
	plugins: [
		alias({
			entries: stdLibBrowser
		}),
		resolve({
			browser: true
		}),
		commonjs(),
		json(),
		inject({
			process: stdLibBrowser.process,
			Buffer: [stdLibBrowser.buffer, 'Buffer']
		})
	],
	onwarn: (warning, rollupWarn) => {
		handleCircularDependancyWarning(warning, rollupWarn);
	}
};

Vite

Show me

Vite config uses combination of Rollup and esbuild plugins. It’s important to use dynamic import when using CommonJS configuration so ESM version of modules is picked up. This allows Vite bundling to use our mocking implementation and implement heuristics such as proper tree-shaking and dead code removal marking.

const inject = require('@rollup/plugin-inject');

const esbuildShim = require.resolve('node-stdlib-browser/helpers/esbuild/shim');

module.exports = async () => {
	const { default: stdLibBrowser } = await import('node-stdlib-browser');
	return {
		resolve: {
			alias: stdLibBrowser
		},
		optimizeDeps: {
			include: ['buffer', 'process']
		},
		plugins: [
			{
				...inject({
					global: [esbuildShim, 'global'],
					process: [esbuildShim, 'process'],
					Buffer: [esbuildShim, 'Buffer']
				}),
				enforce: 'post'
			}
		]
	};
};

esbuild

Show me

Using esbuild requires you to use helper utilities and plugins.

const path = require('path');
const esbuild = require('esbuild');
const plugin = require('node-stdlib-browser/helpers/esbuild/plugin');
const stdLibBrowser = require('node-stdlib-browser');

(async () => {
	await esbuild.build({
		// ...
		inject: [require.resolve('node-stdlib-browser/helpers/esbuild/shim')],
		define: {
			global: 'global',
			process: 'process',
			Buffer: 'Buffer'
		},
		plugins: [plugin(stdLibBrowser)]
	});
})();

Browserify

Show me

Bundling ES modules is currently not supported natively in Browserify, but you can try using esmify or babelify for transforming to CommonJS first.

const fs = require('fs');
const path = require('path');
const browserify = require('browserify');
const aliasify = require('aliasify');
const stdLibBrowser = require('node-stdlib-browser');

const b = browserify(
	[
		/* ... */
	],
	{
		// ...
		transform: [[aliasify, { aliases: stdLibBrowser }]],
		insertGlobalVars: {
			process: () => {
				return `require('${stdLibBrowser.process}')`;
			},
			Buffer: () => {
				return `require('${stdLibBrowser.buffer}').Buffer`;
			}
		}
	}
);

Package contents

Module Browser implementation Mock implementation Notes
assert assert
buffer buffer buffer buffer@5 for IE 11 support
child_process
cluster
console console-browserify console
constants constants-browserify
crypto crypto-browserify
dgram
dns dns
domain domain-browser
events events
fs Mocking fs
http stream-http
https https-browserify
module
net net
os os-browserify
path path-browserify
process process process
punycode punycode punycode@1 for browser support
querystring querystring-es3 Contains additional exports from newer Node versions
readline
repl
stream stream-browserify
string_decoder string_decoder
sys util
timers timers-browserify
timers/promises isomorphic-timers-promises
tls tls
tty tty-browserify tty
url node-url Contains additional exports from newer Node versions (URL and URLSearchParams are not polyfilled)
util util
vm vm-browserify
zlib browserify-zlib
_stream_duplex readable-stream
_stream_passthrough readable-stream
_stream_readable readable-stream
_stream_transform readable-stream
_stream_writable readable-stream

API

packages

Returns: object

Exports absolute paths to each module directory (where package.json is located), keyed by module names. Modules without browser replacements return module with default export null.

Some modules have mocks in the mock directory. These are replacements with minimal functionality.

Tips

Mocking fs

fs package doesn’t return anything since there are many different ways you can implement file system functionality in browser.

Examples of implementations:

Node support

Minimum supported version should be Node 10.

If you’re using ESM in Node < 12.20, note that subpath patterns are not supported so mocks can’t be handled. In that case, it’s recommended to use CommonJS implementation.

Browser support

Minimum supported version should be Internet Explorer 11, but most modules support even Internet Explorer 9.

Types

You can use default @types/node types.

License

MIT © Ivan Nikolić

More Repositories

1

throttle-debounce

Throttle and debounce functions.
JavaScript
975
star
2

x-autosuggest

Autosuggest results based on input.
JavaScript
66
star
3

postcss-em-media-query

PostCSS plugin for transforming min/max-width/height media queries to ems.
JavaScript
25
star
4

stylelint-no-restricted-syntax

Stylelint rule to disallow specified syntax.
JavaScript
19
star
5

isomorphic-timers-promises

`timers/promises` for client and server.
JavaScript
18
star
6

modernizr-esm

Modernizr tests as ES Modules.
JavaScript
17
star
7

get-sass-vars

Get Sass variables as JSON object.
JavaScript
17
star
8

read-safari-reading-list

Read and parse Safari Reading List.
JavaScript
16
star
9

babel-plugin-native-error-extend

Babel plugin for native `Error` extending.
JavaScript
12
star
10

postcss-query-ast

Query PostCSS AST with CSS selectors.
JavaScript
12
star
11

dotfiles

Home is where the dotfiles are.
Shell
9
star
12

stylelint-no-unresolved-module

Ensures that module (import-like or `url`) can be resolved to a module on the file system.
JavaScript
8
star
13

rationalize.css

Opinionated additions to Normalize.
HTML
8
star
14

sync-safari-reading-list-cli

Sync Safari Reading List to Pinboard bookmarking service.
JavaScript
7
star
15

addic7ed-subtitles-api

API for Addic7ed subtitles.
HTML
6
star
16

babel-plugin-transform-globalthis

Babel plugin for transforming `globalThis`.
JavaScript
5
star
17

browserify-require-async

Browserify transform to handle require.async calls.
JavaScript
5
star
18

sync-safari-reading-list

Sync Safari Reading List to Pinboard bookmarking service.
JavaScript
5
star
19

fetch-google-maps

Load Google Maps API.
JavaScript
4
star
20

jsonapi-data-manager

Handle JSON API data.
JavaScript
4
star
21

stylelint-sass-render-errors

Display Sass render errors and deprecations as lint errors.
JavaScript
3
star
22

string-replace-all-ponyfill

`String.prototype.replaceAll` ponyfill.
JavaScript
3
star
23

array-group-by-ponyfill

`Array.prototype.groupBy` ponyfill.
JavaScript
3
star
24

only-last-promise

Resolve or reject only last Promise.
JavaScript
3
star
25

native-querystring

Node’s querystring module implemented using the built-in URLSeachParams API.
JavaScript
3
star
26

stylelint-number-z-index-constraint

Stylelint rule for setting minimum and maximum constraint value for z-index.
JavaScript
3
star
27

array-string-at

Array/string `.at()` ponyfill.
JavaScript
3
star
28

tv-shows-cli

Personal TV shows manager.
JavaScript
2
star
29

sass-scoped-media-query

Scope CSS styles and apply them only inside provided selector and media query pairs.
SCSS
2
star
30

docker-plex-oauth

Docker image for Plex OAuth support.
JavaScript
2
star
31

array-group-by-to-map-ponyfill

`Array.prototype.groupByToMap` ponyfill.
JavaScript
2
star
32

homebrew-pljoska

Personal Homebrew formulae.
Ruby
2
star
33

knowledge

Guides, instructions, tips. Just general development knowledge.
2
star
34

papir.css

Sensible print stylesheet.
HTML
2
star
35

eslint-config-nitpick

ESLint config for my projects.
JavaScript
2
star
36

statua-dialog

Dialog component.
JavaScript
2
star
37

promise-any-ponyfill

`Promise.any` ponyfill.
JavaScript
2
star
38

tint-shade-color

Tint or shade color.
JavaScript
2
star
39

regex-oib

Regular expression for OIB.
JavaScript
2
star
40

stylelint-config-nitpick

Stylelint config for my projects.
JavaScript
2
star
41

delegate-event-listener

Delegate event listener.
JavaScript
2
star
42

ping-home

Sham-like alternative to Beacon API (http://mdn.io/beacon)
JavaScript
2
star
43

css-resolution-units

List of CSS resolution units.
2
star
44

postcss-media-query-gap

PostCSS plugin for applying gap on max-width/height media queries.
JavaScript
2
star
45

sort-media-queries

Sort media queries.
JavaScript
2
star
46

node-sass-global-import-once

Import Sass files once globally.
JavaScript
2
star
47

docker-node-chrome

Docker image with Node and latest Google Chrome.
Shell
2
star
48

bookmarklets

List of bookmarklets I find useful. Also, easy iOS activation of those same bookmarklets.
JavaScript
2
star
49

element-within-viewport

Check if elements are in viewport.
JavaScript
2
star
50

css-angle-units

List of CSS angle units.
1
star
51

string-match-all

`String.prototype.matchAll` ponyfill.
JavaScript
1
star
52

load-script-p

Load script as promise.
JavaScript
1
star
53

babel-plugin-media-query-gap

Babel plugin for applying gap on max-width/height media queries.
JavaScript
1
star
54

advertol

Advertisement zones manager.
1
star
55

vagrant-selenium

Setup simple Selenium server via Vagrant.
Shell
1
star
56

css-time-units

List of CSS time units.
1
star
57

css-inliner

JavaScript
1
star
58

hascheck

Interface to Hrvatski akademski spelling checker.
JavaScript
1
star
59

delay-image

Delay image load until it’s in viewport.
JavaScript
1
star
60

css-frequency-units

List of CSS frequency units.
1
star
61

css-functions-list

List of standard and browser specific CSS functions.
JavaScript
1
star
62

regex-jmbg

Regular expression for JMBG.
JavaScript
1
star
63

exfetch

Enhanced (un)fetch API which supports abort and progress events.
JavaScript
1
star
64

babayaga

Convenient Browserify builds.
JavaScript
1
star
65

faux-anchor

Improve anchor and non-anchor elements with primary and secondary actions and callbacks.
JavaScript
1
star
66

playground

Testing, testing…
JavaScript
1
star
67

node-sass-json-functions

JSON encode and decode functions for node-sass.
JavaScript
1
star
68

st-settings

Sublime Text personal settings.
TypeScript
1
star
69

tv-shows

Personal TV shows manager.
JavaScript
1
star
70

babel-plugin-transform-object-hasown

Babel plugin for transforming `Object.hasOwn`.
JavaScript
1
star
71

postcss-escape-generated-content-string

PostCSS plugin for escaping strings in generated content.
JavaScript
1
star
72

parse-human-date-range

Parse human-readable date to range of dates.
JavaScript
1
star
73

kist-selectdown

Select with customizable menu.
JavaScript
1
star
74

regex-css-media-query

Regular expression for CSS media query.
JavaScript
1
star
75

kist-tabify

Simple tabs and accordion interface.
JavaScript
1
star
76

parse-safari-reading-list

[UNMAINTAINED] - Parse Safari Reading List and publish it to Pinboard.
JavaScript
1
star
77

webpack-config-niksy

[DEPRECATED] Webpack config for my projects.
JavaScript
1
star
78

generator-paleta

Yeoman generator for my projects.
JavaScript
1
star
79

classlist-multiple-values

Use multiple values for `classList.add` and `classList.remove` methods.
JavaScript
1
star
80

LSP-sass

Sass support for Sublime’s LSP plugin
Python
1
star