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.
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.
{
"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:
{
"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.