Sub topic 14
Packages, npm, and Bundlers
This chapter assumes you can write ES modules and CommonJS modules, run scripts with the node command, and load a module script in an HTML page. Earlier chapters covered all three. Here you will add third-party code to a project with npm, see how Node.js finds that code on disk, and learn why the browser usually needs a bundler to use the same packages.
What a package is
A package is a directory with a package.json file in it. That file describes the code: its name, version, entry points, and the other packages it depends on. npm (the Node Package Manager) is the command-line tool that ships with Node.js. It downloads packages from the public npm registry and installs them into your project.
Start a project and install a dependency:
mkdir dates-demo
cd dates-demo
npm init -y
npm pkg set type=module
npm install date-fns
npm install --save-dev esbuildAfter these commands the project contains three new things:
| Item | What it is | Commit to version control? |
|---|---|---|
| `package.json` | Your project's manifest, edited by you and by npm | Yes |
| `package-lock.json` | The exact version of every installed package, including indirect ones | Yes |
| `node_modules/` | The downloaded package code | No, add it to `.gitignore` |
The resulting package.json looks roughly like this:
{
"name": "dates-demo",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node src/main.js",
"build": "esbuild src/main.js --bundle --format=esm --minify --outfile=dist/bundle.js"
},
"dependencies": {
"date-fns": "^4.1.0"
},
"devDependencies": {
"esbuild": "^0.24.0"
}
}The scripts block was added by hand. Your installed version numbers may differ.
dependencies versus devDependencies
dependencies lists packages your code needs when it runs. devDependencies lists tools you only need while developing, such as bundlers, test runners, and linters. The difference matters for anyone who installs your package as a library: npm installs your dependencies for them, but not your devDependencies. On a production server, npm ci --omit=dev skips dev tools completely.
Version ranges and the lockfile
npm versions follow semantic versioning (semver), written MAJOR.MINOR.PATCH. A major bump signals breaking changes. A minor bump adds features without breaking anything. A patch bump fixes bugs. The entries in package.json are ranges, not exact versions:
| Range | Matches | Notes |
|---|---|---|
| `^4.1.0` | `>=4.1.0 <5.0.0` | npm's default; accepts minor and patch updates |
| `~4.1.0` | `>=4.1.0 <4.2.0` | Patch updates only |
| `4.1.0` | Exactly `4.1.0` | Pinned |
| `^0.24.0` | `>=0.24.0 <0.25.0` | Below 1.0, the caret treats the minor number as breaking |
Because ranges are loose, two people running npm install a month apart could get different code. The lockfile fixes this. package-lock.json records the exact version, download URL, and integrity hash of every package in the tree.
npm installresolves ranges, may update the lockfile, and installs.npm ciinstalls exactly what the lockfile says. It deletesnode_modulesfirst and fails if the lockfile andpackage.jsondisagree. Use it in CI and in deployments.
How Node.js finds a package
Write a small program that uses the package:
// src/main.js
import { format, addDays } from 'date-fns';
const start = new Date(2026, 0, 15);
console.log(format(start, 'yyyy-MM-dd'));
console.log(format(addDays(start, 30), 'EEEE, MMMM d'));Run it with npm start (or node src/main.js). It prints:
2026-01-15
Saturday, February 14The string 'date-fns' is a bare specifier: it is not a relative path like './math.js' and not a URL. Node.js resolves bare specifiers by looking for node_modules/date-fns in the importing file's directory, then in its parent, then the parent's parent, up to the filesystem root. Once it finds the package directory, it reads that package's package.json to choose the entry file.
The exports field and conditions
Modern packages declare their entry points in an exports field. It can point to different files depending on how the package is loaded:
{
"name": "tiny-lib",
"version": "1.0.0",
"exports": {
".": {
"browser": "./dist/browser.js",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./utils": "./dist/utils.mjs"
}
}These keys are called conditions. Node.js matches import when the package is loaded with an import statement and require when it is loaded with require(). It never matches browser, but bundlers targeting the web do. Keys are checked in order and the first match wins, so put the specific conditions before the general ones. This is how one package can ship both an ES module build and a CommonJS build.
exports also encapsulates the package. Only the listed paths can be imported. import 'tiny-lib/utils' works, but import 'tiny-lib/dist/internal.js' fails with ERR_PACKAGE_PATH_NOT_EXPORTED, even though the file exists. Older packages that lack exports fall back to the main field and allow deep imports of any file.
Running package tools
Packages can ship command-line tools. npm links them into node_modules/.bin, and there are two ways to run them:
npx esbuild --version
npm run buildnpx runs a binary from the local node_modules/.bin, or downloads the package temporarily if it is not installed. npm run <name> runs an entry from scripts, and puts node_modules/.bin on the PATH while it does. That is why the build script can just say esbuild with no path. npm start and npm test are shortcuts for npm run start and npm run test.
Why the browser needs more
Try loading the same src/main.js in a page with <script type="module" src="src/main.js">. The console shows an error similar to:
Uncaught TypeError: Failed to resolve module specifier "date-fns".
Relative references must start with either "/", "./", or "../".The browser has no node_modules lookup. It only loads URLs. Even if it did, a real dependency tree can contain hundreds of small files, and fetching each one over the network, one import level at a time, would make the page slow to start.
A bundler fixes this. It starts from your entry file, follows every import and require the same way Node.js would, and writes out one file (or a few) the browser can load directly.
Run the build and point the page at its output:
npm run build<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dates</title>
<script type="module" src="dist/bundle.js"></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>Serve the folder with any static server, for example npx serve .. Module scripts do not load from file:// URLs. The console shows the same two lines Node.js printed.
What a bundler does besides concatenating
| Job | What it means | Why it helps |
|---|---|---|
| Resolution | Applies Node-style lookup and `exports` conditions, including `browser` | Bare specifiers work |
| Tree shaking | Removes exports nothing imports | `date-fns` has hundreds of functions; only `format` and `addDays` ship |
| Minification | Shortens names, strips whitespace | Fewer bytes to download |
| Transformation | Compiles TypeScript, JSX, or newer syntax for older browsers | One source, many targets |
| Format conversion | Wraps CommonJS packages so ES module code can import them | Old packages still work in the browser |
| Code splitting | Emits separate chunks for dynamic `import()` | Load code only when it is needed |
Tree shaking only works well on ES modules. Their import and export statements are static, so the bundler can see what is used without running anything. With CommonJS, require() is an ordinary function call and module.exports can be changed at runtime, so the bundler usually has to keep the whole module.
Common bundlers include esbuild, Rollup, webpack, and Vite. Vite uses Rollup for production builds and serves native modules during development. They differ in speed, plugin ecosystems, and how much configuration they need. All of them do the jobs in the table.
Skipping the bundler: import maps
For small projects you can tell the browser how to resolve bare specifiers yourself:
<script type="importmap">
{
"imports": {
"date-fns": "https://esm.sh/[email protected]"
}
}
</script>
<script type="module" src="src/main.js"></script>The import map must appear before any module script that uses it. This works without a build step, but you get no tree shaking, you depend on a CDN, and the browser still fetches many files.
Common errors
| Symptom | Likely cause |
|---|---|
| `Cannot find package 'x'` or `Cannot find module 'x'` in Node.js | Package not installed, or you ran the script from a directory with no `node_modules` above it |
| `Failed to resolve module specifier` in the browser | Bare import without a bundler or import map |
| `ERR_PACKAGE_PATH_NOT_EXPORTED` | Deep import into a path the package's `exports` does not list |
| `require() of ES Module ... not supported` | Calling `require` on an ESM-only package in a Node.js version that cannot do that; use `import` or `await import()` |
| Works locally, breaks in CI | CI ran `npm install` and got newer versions, or the lockfile was not committed; use `npm ci` |
| Bundle includes `fs` or `process` errors | A Node-only package was bundled for the browser; pick a browser-compatible package |
Recent Node.js versions (22.12 and later) can require() synchronous ES modules, so the fifth error depends on the version you run.
Exercise
A package.json lists "chalk": "^5.3.0" and "esbuild": "^0.24.2". Which of these versions can npm install for each: chalk 5.4.1, chalk 6.0.0, esbuild 0.24.9, esbuild 0.25.0?
Show answer
chalk 5.4.1 is allowed, because ^5.3.0 means >=5.3.0 <6.0.0. chalk 6.0.0 is not allowed. esbuild 0.24.9 is allowed. esbuild 0.25.0 is not allowed, because below 1.0 the caret treats the minor number as breaking, so ^0.24.2 means >=0.24.2 <0.25.0.
Exercise
A package's exports field is { ".": { "import": "./esm/index.js", "require": "./cjs/index.js" } }. Which file does Node.js load for import x from 'pkg', which for require('pkg'), and what happens with import 'pkg/esm/helpers.js'?
Show answer
The import statement loads ./esm/index.js through the "import" condition. require('pkg') loads ./cjs/index.js through the "require" condition. The deep import fails with ERRPACKAGEPATHNOTEXPORTED, because the exports field only exposes ".".
Exercise
Your teammate says the bundle is too large because it includes an entire utility library, even though the code only calls one function. The library publishes only a CommonJS build. Explain why tree shaking did not help and suggest two fixes.
Show answer
Tree shaking relies on static import and export statements. CommonJS builds export through module.exports, which can change at runtime, so the bundler cannot safely prove which parts are unused and keeps the whole module. Fixes include switching to the library's ES module build or an ESM alternative (for example lodash-es instead of lodash), importing a per-function entry point if the package offers one, or writing the small function yourself.