Skip to content

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.

16 min read0/4 questions

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));
}

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 CURRENCY from cart.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.

Quick check
dates.js contains only export function formatDate(d) { ... }. Which line imports it correctly?
Need a nudge? A hint rules out a wrong answer.

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-clicking index.html and 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 example npx serve or 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 developing
What npm install does
YounpmRegistryYour projectnpm install date-fnslatest date-fns?tarball + its depswrite node_modules/update package.jsonupdate package-lock.json

You ask for a package by name.

1/6

After that, your project looks like this:

A small npm project
  • 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"
  }
}
  • dependencies are needed when the app runs: libraries your code imports.
  • devDependencies are only needed while developing: test runners, bundlers, linters, TypeScript. A server running a Node app in production can skip them.
  • scripts are named commands for the project.
Match the pairs0/4 matched

Match each file or folder to its job.

Choose an item, then its match on the other side.

Semantic versioning

Package versions follow semantic versioning (semver): three numbers, MAJOR.MINOR.PATCH, with a promise about what each change means.

PartBumped whenExample
MAJORSomething changed that may break your code3.6.0 to 4.0.0
MINORA new feature was added, nothing broke4.0.0 to 4.1.0
PATCHA bug was fixed, nothing else changed4.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): any 4.x.x from 4.1.0 up. Minor and patch updates, never a new major.
  • ~4.1.0 (tilde): any 4.1.x from 4.1.0 up. 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:

JavaScript
function parse(version) { return version.split(".").map(Number);} // Does `version` satisfy the caret range `^base`?function satisfiesCaret(version, base) { const [major, minor, patch] = parse(version); const [bMajor, bMinor, bPatch] = parse(base); if (major !== bMajor) return false; if (bMajor === 0 && minor !== bMinor) return false; // 0.x is stricter if (minor !== bMinor) return minor > bMinor; return patch >= bPatch;} const range = "4.1.0";for (const v of ["4.1.0", "4.1.7", "4.9.2", "5.0.0", "4.0.9"]) { console.log(`^${range} allows ${v}?`, satisfiesCaret(v, range));}console.log("^0.3.1 allows 0.4.0?", satisfiesCaret("0.4.0", "0.3.1")); // Why versions need numeric comparison, not string sortingconst versions = ["1.10.0", "1.2.0", "1.9.3"];console.log(versions.toSorted());console.log( versions.toSorted((a, b) => { const [x, y] = [parse(a), parse(b)]; return x[0] - y[0] || x[1] - y[1] || x[2] - y[2]; }));
Output
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.

Quick check
package.json lists "chart-lib": "^2.3.1". Which version could npm install pick when there is no lock file?
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
const pkg = { name: "recipe-app", scripts: { dev: "vite", build: "vite build", test: "vitest" }, dependencies: { "date-fns": "^4.1.0", "canvas-confetti": "~1.9.3" }, devDependencies: { vite: "^7.0.0", prettier: "3.6.2" },}; function describeRange(range) { if (range.startsWith("^")) return "minor and patch updates"; if (range.startsWith("~")) return "patch updates only"; return "this exact version";} const all = { ...pkg.dependencies, ...pkg.devDependencies };for (const [name, range] of Object.entries(all)) { const where = name in pkg.dependencies ? "runtime" : "dev only"; console.log(`${name.padEnd(16)}${range.padEnd(8)}${where.padEnd(10)}${describeRange(range)}`);} console.log("Commands:", Object.keys(pkg.scripts).map((s) => `npm run ${s}`).join(", "));
Output
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 once
Quick check
A new teammate clones the repo and runs npm run dev. It fails with vite: command not found. What did they most likely skip?
Need a nudge? A hint rules out a wrong answer.
Key terms
ES module
A JavaScript file with its own scope that shares values with export and uses others with import.
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. devDependencies are only needed while developing.
semver
MAJOR.MINOR.PATCH versioning: 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.