Lesson 17 of 50JavaScript in depth
Modules and npm
Split code into ES modules with import and export, load them in the browser, and manage packages with npm, package.json, semver and scripts.
Small examples fit in one file. Real projects do not: a modest web app has hundreds of files of its own, plus thousands more written by other people. Two systems make that manageable. Modules let each file keep its own variables private and share only what it chooses, so a name in one file cannot accidentally clash with the same name in another. npm lets you install other people's code (a date library, a testing tool, React itself) with one command, and keeps track of exactly which versions your project uses. This lesson covers both, from your first import to reading a package.json like an experienced developer. The TypeScript side of modules (type imports, tsconfig.json and declaration files) comes later, in the modules and tsconfig lesson.
Why modules
Before modules, every <script> tag on a page shared one big global scope. If cart.js and analytics.js both declared a function called track, whichever loaded second silently replaced the first. Teams worked around it with naming conventions and wrapper functions, and it was fragile.
An ES module (ES for ECMAScript, the official name of the JavaScript standard) is simply a file that uses import or export. Each module has its own scope: its top-level variables are private unless it exports them. To use something from another file, you import it by name, so every dependency is written at the top of the file for anyone to see.
export and import
There are two kinds of export. A named export shares a value under its own name; a file can have as many as it likes. A default export is the file's one main value, and the importing file chooses what to call it.
// Named exports
export const CURRENCY = "USD";
export function formatPrice(cents) {
return `$${(cents / 100).toFixed(2)}`;
}
// Private: not exported, so no other file can use it
function round(n) {
return Math.round(n);
}
// Default export: one per file
export default function addTax(cents, rate = 0.2) {
return round(cents * (1 + rate));
}// Default import (any name) plus named imports (exact names)
import addTax, { formatPrice, CURRENCY } from "./money.js";
// Rename a named import if it clashes
import { formatPrice as fmt } from "./money.js";
// Everything at once, as one object
import * as money from "./money.js";
console.log(formatPrice(addTax(1000)), CURRENCY);
console.log(fmt(250), money.CURRENCY);Rules worth remembering:
- Named imports use braces and the exact exported name.
import { formatprice }(wrong case) gives you an error, which is good: typos are caught immediately. - A default import has no braces, and you can name it anything. That freedom is also its weakness, since the same function can end up called three different things in three files. Many teams prefer named exports everywhere, except where a framework requires a default (Next.js does for its page files).
- Imports are read-only bindings. You cannot reassign
CURRENCYfromcart.js. - A module runs once. However many files import
money.js, its top-level code runs a single time, and they all share the same values. That makes a module a natural home for shared configuration or a single database connection.
There is also a dynamic import, import("./chart.js"), which loads a module on demand and returns a promise. Bundlers use it to split a large app so code for a rarely used page is only downloaded when someone opens it.
dates.js contains only export function formatDate(d) { ... }. Which line imports it correctly?Modules in the browser
To load a module in a web page, add type="module" to the script tag:
<script type="module" src="./cart.js"></script>Module scripts behave differently from classic ones:
- They are deferred: the browser waits until the HTML is parsed before running them, so the elements already exist.
- They run in strict mode automatically, which turns some silent mistakes into errors.
- Import paths are URLs. Relative imports must start with
./or../and in the browser need the file extension ("./money.js", not"./money"). - They do not work from
file://. Double-clickingindex.htmland seeing a CORS error in the console is a rite of passage. Browsers only load modules over HTTP, so run a small local server, for examplenpx serveor the Live Server extension in VS Code. - A bare name like
import confetti from "canvas-confetti"does not work on its own in the browser, because the browser does not know where npm put that package. That is one of the jobs a bundler (Vite, webpack, or the one built into Next.js) does for you.
Node.js supports ES modules too. Files ending in .mjs are always modules, and adding "type": "module" to package.json makes every .js file in the project one. Older Node code uses a different system called CommonJS (require() and module.exports), which you will still meet in tutorials and older packages.
npm: other people's code
npm (originally "Node package manager") is two things: a public registry holding millions of open-source packages, and a command-line tool that installs them. It comes with Node.js, so if node --version works, so does npm --version.
Start a project and install something:
mkdir recipe-app && cd recipe-appnpm init -y # create package.json with default answersnpm install date-fns # a runtime dependencynpm install --save-dev vitest # a tool only needed while developingYou ask for a package by name.
After that, your project looks like this:
- recipe-app/
- package.jsonname, scripts, dependency ranges
- package-lock.jsonexact versions installed: commit it
- node_modules/downloaded packages: never commit it
- date-fns/
- vitest/
- .bin/command-line tools from packages
- .gitignorecontains node_modules/
- index.html
- src/
- main.js
- money.js
node_modules can easily hold hundreds of megabytes, and anyone can recreate it from the lock file, so it always goes in .gitignore. When you clone a project, run npm install (or npm ci, the strict version used on build servers, which installs exactly what the lock file says and fails if it disagrees with package.json).
Reading package.json
{
"name": "recipe-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "vitest"
},
"dependencies": {
"date-fns": "^4.1.0"
},
"devDependencies": {
"vite": "^7.0.0",
"vitest": "^3.2.0"
}
}dependenciesare needed when the app runs: libraries your code imports.devDependenciesare only needed while developing: test runners, bundlers, linters, TypeScript. A server running a Node app in production can skip them.scriptsare named commands for the project.
Match each file or folder to its job.
Semantic versioning
Package versions follow semantic versioning (semver): three numbers, MAJOR.MINOR.PATCH, with a promise about what each change means.
| Part | Bumped when | Example |
|---|---|---|
| MAJOR | Something changed that may break your code | 3.6.0 to 4.0.0 |
| MINOR | A new feature was added, nothing broke | 4.0.0 to 4.1.0 |
| PATCH | A bug was fixed, nothing else changed | 4.1.0 to 4.1.1 |
The symbol in front of a version in package.json is a range, meaning "any version in this window is acceptable":
^4.1.0(caret, npm's default): any4.x.xfrom4.1.0up. Minor and patch updates, never a new major.~4.1.0(tilde): any4.1.xfrom4.1.0up. Patch updates only.4.1.0(no symbol): exactly that version.
One exception: below 1.0.0, a package is considered unstable, so ^0.3.1 only allows 0.3.x. Here is the caret rule as code:
Press Run (⌘ Enter) to see what happens.Try changing range to "0.3.1" and see how few versions are allowed. The real npm uses a package called semver with many more rules, but these are the ones you need day to day. Semver is a promise made by humans, so a minor release occasionally breaks things anyway. That is exactly why the lock file exists: your project keeps the versions you tested until you choose to update.
package.json lists "chart-lib": "^2.3.1". Which version could npm install pick when there is no lock file?A package.json file is plain JSON, so code can read it like any other object. This is a small version of what tools like npm outdated do: list each dependency, where it is used, and how much freedom its range gives npm.
Press Run (⌘ Enter) to see what happens.Change prettier to "~3.6.2" and run it again.
Scripts and npx
The scripts field gives your project short, shared commands. Run them with npm run <name>: npm run dev, npm run build. Two names have shortcuts, npm test and npm start. While a script runs, npm adds node_modules/.bin to the command path, which is why "dev": "vite" works even though you never installed Vite globally.
npx runs a package's command without adding it to your project. If the package is not installed, npx downloads it to a cache first. It is how project starters work:
npx serve . # a quick static file server for this foldernpm create vite@latest # npm create runs the create-vite starternpx prettier --write . # run a tool oncenpm run dev. It fails with vite: command not found. What did they most likely skip?- ES module
- A JavaScript file with its own scope that shares values with
exportand uses others withimport. - named vs default export
- Named exports are imported by exact name in braces; the single default export can be imported under any name.
- npm
- The package registry for JavaScript and the command-line tool that installs from it.
- dependency
- A package your project needs.
devDependenciesare only needed while developing. - semver
MAJOR.MINOR.PATCHversioning: breaking change, new feature, bug fix.- lock file
package-lock.json: the exact installed version of every package, so installs are repeatable.- npx
- Runs a package's command, downloading it first if needed, without adding it to the project.