Handbooks / Node.js / Chapter 1
Modules and npm
7 pages · ~5 min✓ Reviewed
Start here. Next up: The Node.js Event Loop.
CommonJS vs ES Modules
1. Loading model
| CommonJS | ESM | |
|---|---|---|
| Syntax | require() / module.exports | import / export |
| Loading | sync, whole file runs at the call, cached in require.cache | parsed first, async |
| Position | anywhere, computed path | hoisted, literal string |
- Conditional load:
import('./x.js')returns a Promise
2. Which system per file
.mjsalways ESM,.cjsalways CJS.js+"type": "module"in nearest package.json = ESM.jsdefault ("commonjs") = CJS
3. Example and gotchas
js
const fs = require('fs'); module.exports = { run };
CJS
js
import fs from 'fs'; export const run = () => {};
ESM
- Relative imports need the extension:
./util.js - No
__dirnameorrequire: useimport.meta.urlorimport.meta.dirname
package.json Essentials
1. Identity and Entry
name+versionrequired to publish; name lowercase, no spacesprivate: trueblocks accidentalnpm publishmain: the CJS entry file"type": "module": .js files become ESMexports: maps subpaths andimport/require; unlisted deep imports blocked; beatsmain
dependencies vs devDependencies
1. Runtime vs Build
| dependencies | devDependencies | |
|---|---|---|
| Needed for | runtime in production (express, react) | build, test, lint (jest, eslint, typescript, vite) |
| Install | npm i pkg | npm i -D pkg |
Semver and Lockfiles
1. Semver and Ranges
- MAJOR.MINOR.PATCH, e.g.
2.4.1 - PATCH: bug fix
- MINOR: backward-compatible feature
- MAJOR: breaking change
| Range | Allows |
|---|
npm Scripts and Everyday Commands
1. Scripts
npm run <name>runs a script; test, start,stopskiprun- node_modules/.bin is on the PATH during a script
- So
"lint": "eslint ."needs no global install
2. Hooks and Arguments
Cheat Sheet: Modules and npm
1. Modules
| CJS | ESM | |
|---|---|---|
| Syntax | require, module.exports | import, export |
| Load | sync, dynamic | static, async |
| Needs |
Check yourself
A file app.mjs runs console.log(__dirname). What happens, and what replaces it?
ReferenceError: ESM has no__dirname.- Use
import.meta.dirname, or derive it fromimport.meta.url.
package.json says ^0.2.3. The registry has 0.2.9, 0.3.0 and 1.0.0. Which version installs?
0.2.9.- Below 1.0.0, ^ pins the minor, because a minor bump may break.