Modules and npm
Real programs are split into many files, and they reuse code other people have written. Modules let your files share code with each other, and npm, the world's largest software registry, gives you millions of ready-made packages.
Splitting code into modules
Each file is a module with its own scope: variables you declare in one file don't leak into others. A module shares things on purpose with export, and another module uses them with import.
In the editors below, a line like // file: math.js starts a new file. The last file is the one that runs:
Default exports
A module can also have one default export, usually the main thing it provides. Import it without braces, under any name you like:
| Syntax | Meaning |
|---|---|
export const x = 1 |
Named export |
export default thing |
The module's default export (at most one) |
import { x } from './a.js' |
Import a named export |
import { x as y } from './a.js' |
Import it under another name |
import thing from './a.js' |
Import the default export |
import * as a from './a.js' |
Import everything as one object |
Relative imports need the file extension: write './math.js', not './math'.
CommonJS: require and module.exports
Before ES modules existed, Node had its own module system called CommonJS. You'll meet it in older tutorials and many existing projects. A file that uses require and the .cjs extension (or a project without "type": "module") is CommonJS:
| ES modules | CommonJS | |
|---|---|---|
| Share code | export |
module.exports = … |
| Use code | import |
require() |
| Loading | Before the code runs (static) | When require runs |
Top-level await |
Yes | No |
| Current file | import.meta.filename, import.meta.dirname |
__filename, __dirname |
Use ES modules for new code. Since Node 22, an ES module can even require() and a CommonJS file can import() the other kind, so mixing them is rarely a problem.
npm and package.json
npm (Node Package Manager) is installed with Node. Every project has a package.json file that describes it:
mkdir shop-api && cd shop-api
npm init -y # creates package.json
npm install express # adds a dependency{
"name": "shop-api",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"test": "node --test"
},
"dependencies": {
"express": "^5.3.0"
},
"devDependencies": {
"eslint": "^10.15.0"
}
}"type": "module"makes every.jsfile in the project an ES module. Add it to new projects.scriptsare shortcuts:npm start,npm run dev,npm test.dependenciesare needed to run the app;devDependencies(npm install -D eslint) only for development: linters, test tools, build tools.
Installing packages
npm install zod # add a dependency
npm install -D vitest # add a dev dependency
npm uninstall zod # remove it
npm install # install everything listed in package.json
npx cowsay "hi" # run a package's command without installing it
npm outdated # see which packages have newer versions
npm audit # check dependencies for known vulnerabilitiesPackages go into the node_modules folder. Never commit node_modules to Git (add it to .gitignore): anyone can recreate it with npm install. Do commit package-lock.json: it records the exact version of every package, so everyone gets an identical install.
Version numbers (semver)
Packages use semantic versioning: MAJOR.MINOR.PATCH.
| Change | Example | Means |
|---|---|---|
| Patch | 5.3.0 → 5.3.1 | Bug fixes only |
| Minor | 5.3.1 → 5.4.0 | New features, still compatible |
| Major | 5.4.0 → 6.0.0 | Breaking changes: read the upgrade guide |
"^5.3.0" in package.json means "5.3.0 or any newer 5.x". npm will take minor and patch updates but never a new major version on its own.
Using a package
Installed packages are imported by name, without ./. The editors in this track include a few popular ones (express, zod, bcryptjs, jsonwebtoken, graphql, cors, helmet and more), so this runs as if you had installed them:
Choosing packages: before adding a dependency, check its weekly downloads, when it was last updated, its open issues and its licence. Every dependency is code you trust with your users' data. If Node has the feature built in (
fetch,node:test,crypto.randomUUID(),node:sqlite), prefer the built-in.
Practice
- Create
strings.jsexportingcapitalize(word)andslugify(title)(lowercase, spaces become dashes), and use both frommain.js. - Give
strings.jsa default export (an object with both functions) and import it withimport strings from './strings.js'. - Rewrite exercise 1 in CommonJS with
.cjsfiles.
1.Which line imports the default export of ./db.js?
2.What does "^5.3.0" allow npm to install?
3.Should node_modules be committed to Git?