Modules, npm & the Ecosystem
JavaScript's real power is its package ecosystem. This module covers how code is organized, shared, installed, and bundled for production.
ES Modules — import / export
Before ES2015, JavaScript had no built-in module system — every script shared one global scope. ES Modules give each file its own scope, with explicit exports and imports.
// math.js export function square(n) { return n * n; } export const PI = 3.14159; export default function add(a, b) { return a + b; } // one default export per file // app.js import add, { square, PI } from "./math.js"; import * as math from "./math.js"; // grab everything as a namespace
<script type="module" src="app.js"> — modules are deferred and strict-mode by default.npm & package.json
npm is JavaScript's package manager and registry, the world's largest — over 3 million packages. package.json declares what your project needs and how to run it.
{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"scripts": { "start": "node index.js", "test": "vitest" },
"dependencies": { "express": "^4.19.0" },
"devDependencies": { "vitest": "^2.0.0" }
}
# npm install express — adds to dependencies, downloads into node_modules/
# npm install -D vitest — adds to devDependencies (dev/test tools only)
# npm run start — runs the "start" script
package.json can silently pull different sub-versions.CommonJS vs ES Modules
Node.js predates ES Modules and used its own system, CommonJS, for years. Both are still common in the wild, and mixing them incorrectly is a frequent source of "unexpected token" errors.
| CommonJS | ES Modules | |
|---|---|---|
| Export | module.exports = x | export default x |
| Import | const x = require("x") | import x from "x" |
| Loading | Synchronous | Supports async, statically analyzable |
| File signal | .cjs, or default in Node | .mjs, or "type": "module" |
Bundlers & Transpilers
Browsers can't efficiently load thousands of separate module files, and not every browser supports every new syntax feature. Bundlers and transpilers solve those two problems.
| Tool | What it does |
|---|---|
| Vite | Fast dev server + bundler, the modern default for new projects |
| webpack | Older, highly configurable bundler — still common in large existing apps |
| esbuild | Extremely fast bundler/minifier written in Go, often used under other tools |
| Babel | Transpiles modern JS syntax down to a version older browsers understand |
| TypeScript | Adds static types on top of JS, compiles (transpiles) back down to plain JS |
Popular Libraries
A handful of packages show up in almost every real-world JavaScript codebase.