Skip to content
jshacks.dev
Packages

Support both Node.js and browsers with the browser field

Swap a Node-only file for a browser build with the package.json browser field, and see why the exports browser condition is the modern choice for bundlers.

1 min read
Summarize in AI

Some libraries have one implementation for Node.js and another for the browser, for example using fs versus fetch. The browser field tells bundlers to replace one file with another.

package.jsonJSON
{
  "name": "my-lib",
  "main": "./dist/node.js",
  "browser": {
    "./dist/node.js": "./dist/browser.js"
  }
}

Node.js itself ignores browser. Bundlers such as webpack and esbuild read it when they target a browser, and swap the file, so import "my-lib" gets browser.js in a web build and node.js on the server.

The newer way is a condition in exports, which Node.js, bundlers and TypeScript all understand:

package.jsonJSON
{
  "exports": {
    ".": {
      "browser": "./dist/browser.js",
      "default": "./dist/node.js"
    }
  }
}

Conditions are checked in order, so browser goes before default. The field is an informal convention, described in the esbuild documentation, and the browser condition is supported there too.

Set "browser": false for a single file to have bundlers replace it with an empty module, which is useful for a Node.js-only import such as fs.

Also inNode.js
Share

More snippets

Packages

Initialize a package with npm init

Initialize a package.json with npm init, skip the questions with the yes flag, and set your own defaults for author and license in npm config.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.