Skip to content

Lesson 30 of 50JavaScript at work

Package Managers, Linters and Bundlers

The JavaScript toolchain at work: npm, pnpm and lockfiles, dependency types, supply-chain attacks and defences, ESLint flat config, formatters and bundlers.

15 min read0/4 questions

You can now build a page in plain JavaScript and talk to APIs from it. This unit is about the code around yours when you join a team. On your first day you clone the repo, run the install command from the README, and wait. Four minutes later there are 1,400 packages in node_modules, and you wrote none of them. Every one of those packages can run code on your laptop during install and ship code to your users. Around them sits a toolchain you are expected to understand: why the team uses pnpm, why CI fails when the lockfile is out of date, why the linter blocks your PR, and what the bundler does to your code before it reaches a browser. In 2025, several attacks spread through npm by stealing developers' tokens, and companies now expect engineers to know the basic defences. This lesson builds on the semver and scripts you learned in Modules and npm.

Package managers and lockfiles

All the major package managers read the same package.json and download from the same registry. They differ in how they lay out node_modules, how fast they are, and what their lockfile looks like.

ToolLockfileWhat sets it apart
npmpackage-lock.jsonShips with Node. The default; works everywhere.
pnpmpnpm-lock.yamlOne shared store on disk, strict node_modules, fast. Popular for monorepos.
Yarn (v4)yarn.lockOptional Plug'n'Play mode with no node_modules at all.
Bunbun.lockVery fast installs; part of the Bun runtime but usable with Node projects.

Whichever one the team uses, use only that one. Running npm install in a pnpm repo creates a second lockfile that disagrees with the first, and now two people can get two different dependency trees from the same commit.

The lockfile is the contract. package.json says "any 4.x of date-fns"; the lockfile says "exactly 4.1.0, from this URL, with this integrity hash". In CI and Docker builds, install strictly from it:

npm ci                          # delete node_modules, install exactly the lockfile, fail if it disagrees with package.jsonpnpm install --frozen-lockfile  # the same idea (pnpm does this by default in CI)

npm install may update the lockfile when ranges allow newer versions; npm ci never does. If CI fails with "lockfile out of sync", someone edited package.json without committing the updated lockfile.

How pnpm is different

npm hoists: it flattens most packages to the top level of node_modules. If you install express, its dependency debug also lands at node_modules/debug, so import debug from "debug" works in your code even though debug is not in your package.json. That is a phantom dependency. It works until express drops debug in a minor release, and your build breaks with no change on your side.

pnpm stores each version of each package once in a global content-addressed store and hard-links it into projects, which saves gigabytes across many repos. Its node_modules contains only your direct dependencies, as symlinks, so a phantom import fails immediately.

pnpm's node_modules after installing express
  • my-api/
  • package.jsonlists express only
  • pnpm-lock.yaml
  • node_modules/
  • express -> .pnpm/express@5.1.0/node_modules/expresssymlink: direct dep
  • .pnpm/every package, each with only its own deps visible
  • express@5.1.0/
  • node_modules/
  • express/hard links into the global store
  • debug -> ../../debug@4.4.1/node_modules/debug
  • debug@4.4.1/
  • node_modules/
  • debug/

import "debug" from your code finds no node_modules/debug, so it fails, which is what you want. Express can still see it, because Node resolves from express's real location inside .pnpm.

Pinning the package manager

The packageManager field in package.json, such as "packageManager": "pnpm@12.15.0", records which tool and version the project uses. Corepack was the Node tool that read this field and fetched the right version automatically. It shipped with Node up to version 24, but Node 25 and later no longer bundle it, so on current Node you install it yourself (npm install -g corepack) or install the package manager directly. Many CI setups, such as the official pnpm GitHub Action, read packageManager on their own.

Kinds of dependencies

  • dependencies: needed when the code runs. Your server imports zod, so it goes here.
  • devDependencies: needed only to build, test or lint: TypeScript, Vitest, ESLint, Vite. For a front-end app that is bundled, the line is blurrier, because the bundler copies what it needs into the output anyway. The split matters most for Node services (a production install can skip dev dependencies with npm ci --omit=dev) and for libraries you publish.
  • peerDependencies: "I need this, but the app must provide it". A React component library lists react as a peer, so the app's single copy is used. If the library listed React as a normal dependency, an app could end up with two copies of React, which breaks hooks with the confusing "Invalid hook call" error.

Duplicates happen with other packages too. npm ls zod or pnpm why zod shows every version in the tree and who pulled it in, and npm dedupe collapses compatible versions. When a dependency of a dependency has a security bug and its parent has not released a fix yet, you can force a version with overrides:

package.json
{
  "overrides": {
    "semver": "^7.7.2"
  }
}

That is npm's field; pnpm has its own overrides setting and Yarn calls it resolutions. Leave a comment in the PR saying why and when it can be removed, because overrides are easy to forget.

Quick check
You are publishing a date-picker component for React apps. Where should react go in its package.json?
Need a nudge? A hint rules out a wrong answer.

Supply-chain attacks

Your code is only as trustworthy as the least careful maintainer in your dependency tree. The common attacks:

  • Typosquatting: publishing axois or lodahs and waiting for someone to mistype an install command. AI coding assistants have added a twist: they sometimes suggest package names that do not exist, and attackers register those names.
  • Compromised maintainers: an attacker steals a real maintainer's npm credentials, often with a convincing phishing email ("your 2FA must be updated"), and publishes a malicious patch version of a popular package. Every project whose range allows that version picks it up on its next fresh install.
  • Install scripts: a package's preinstall or postinstall script runs with your user's permissions the moment you install it, before you have imported anything.

2025 showed how these combine. In September, phishing gave attackers control of a maintainer account that published widely used small packages such as chalk and debug, and malicious versions were briefly published with code that tried to steal cryptocurrency in users' browsers. Days later a self-spreading worm, named Shai-Hulud by researchers, used install scripts to steal npm and GitHub tokens from developers' machines and CI runners, then used each stolen npm token to publish infected versions of other packages that person maintained. Further waves followed later in the year. npm responded by tightening tokens and pushing trusted publishing, where CI publishes with short-lived credentials instead of a long-lived token.

This tool shows the idea behind the typosquat checks that security scanners run on new dependencies:

JavaScript
// Flag new dependencies whose names are suspiciously close to popular ones.const POPULAR = ["react", "lodash", "express", "axios", "chalk", "debug", "zod", "dotenv"]; function distance(a, b) { // Levenshtein: the fewest single-letter edits that turn a into b const row = Array.from({ length: b.length + 1 }, (_, j) => j); for (let i = 1; i <= a.length; i++) { let prev = row[0]; row[0] = i; for (let j = 1; j <= b.length; j++) { const temp = row[j]; row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = temp; } } return row[b.length];} function review(name) { if (POPULAR.includes(name)) return `${name}: ok (known package)`; const close = POPULAR.find((p) => distance(name, p) <= 2 && Math.abs(name.length - p.length) <= 2); if (close) return `${name}: SUSPICIOUS, one or two edits from "${close}"`; return `${name}: unknown, check downloads, repo and maintainers`;} const newDeps = ["axios", "axois", "lodahs", "expresss", "dotenv", "date-fns", "preact"];newDeps.forEach((d) => console.log(review(d)));
Output
Press Run (⌘ Enter) to see what happens.

Notice preact: a real, respected library, flagged because it is one letter from react. Name checks are a cheap first filter that a human then reviews, never a verdict.

Defences that actually help

No single setting stops every attack. Layers do:

  1. Commit the lockfile and install with npm ci everywhere except when you mean to update. A new malicious version cannot reach a build that only installs pinned, hash-checked versions.
  2. Review lockfile changes in PRs. A one-line package.json change that adds 40 packages to the lockfile deserves a question.
  3. Turn off install scripts by default. npm ci --ignore-scripts, or ignore-scripts=true in .npmrc. pnpm 10 and later already refuse to run dependencies' build scripts unless you approve them (pnpm approve-builds). A few packages genuinely need scripts to compile native code; allow those by name.
  4. Wait before adopting brand-new versions. Most malicious releases are found and removed within hours or days. Recent npm has a min-release-age setting and pnpm has minimumReleaseAge, so installs skip versions younger than a delay you choose. Check your tool's docs for the units and exact name.
  5. Automate updates with Renovate or Dependabot, grouped and on a schedule, so you update often in small reviewed steps instead of once a year in a panic.
  6. Scan. npm audit checks your tree against known vulnerabilities. It is noisy (a vulnerability in a dev-only tool may not matter), so triage by whether the vulnerable code actually ships or runs. npm audit signatures verifies registry signatures and provenance attestations.
  7. Limit what a token can do. CI tokens should be short-lived and scoped; publish through trusted publishing with provenance, which links a package version to the exact repo and CI run that built it.
Put it in order5 steps

A package in your lockfile is reported as compromised. Put the response in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Linting and formatting

A linter finds code that is probably wrong. A formatter decides how code looks. Keep the jobs separate: a linter rule about semicolons just creates noise that a formatter would have fixed silently.

ESLint is the standard linter. Current ESLint uses only the flat config format, a single eslint.config.js that exports an array of config objects; the old .eslintrc files are no longer supported in ESLint 10. With TypeScript, add typescript-eslint, and turn on its type-aware rules, which use the type checker to find bugs that syntax alone cannot show:

eslint.config.js
import js from "@eslint/js";
import { defineConfig, globalIgnores } from "eslint/config";
import tseslint from "typescript-eslint";
 
export default defineConfig([
  globalIgnores(["dist/", "coverage/"]),
  js.configs.recommended,
  tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: {
      parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
    },
  },
]);

The rule that earns its keep is no-floating-promises. It flags saveOrder(1); when saveOrder is async and nothing awaits it or handles its errors. That bug loses data silently in production and is almost invisible in review. Type-aware linting is slower, so large repos run it in CI and in the editor rather than on every keystroke.

For formatting, Prettier is the long-standing default. Biome is a single fast tool written in Rust that formats and lints, and oxlint is a very fast Rust linter that some teams run alongside or instead of ESLint. The choice matters far less than having one, enforced automatically:

  • Format on save in the editor, using the project's config, not personal settings.
  • A pre-commit hook with husky and lint-staged that runs the formatter and linter on staged files only, so it takes seconds.
  • CI runs the same checks (prettier --check ., eslint .), because hooks can be skipped with --no-verify.

Bundlers

Browsers can load ES modules directly, so why bundle? Because an app with 2,000 modules and their imports would need thousands of requests, bare imports like "react" mean nothing to a browser, and TypeScript and JSX must become JavaScript first. A bundler does five jobs:

What a bundler does to your code
main.tsx: entry pointmain.tsxentry pointResolve: find every importResolvefind every importTransform: TS, JSX, CSS to JSTransformTS, JSX, CSS to JSTree shake: drop unused exportsTree shakedrop unused exportsSplit: chunks per routeSplitchunks per routeMinify: smaller outputMinifysmaller outputdist/: hashed files + mapsdist/hashed files + mapswrite

Resolve: starting from the entry, follow every import to a real file, using package.json exports fields and your path aliases.

1/5

Tree shaking in miniature:

JavaScript
// Tree shaking, in miniature: keep only exports reachable from the entry.const modules = { "main.js": { imports: { "utils.js": ["formatPrice"] }, uses: [] }, "utils.js": { exports: { formatPrice: { size: 120, uses: ["round"] }, round: { size: 40, uses: [] }, parseCsv: { size: 2400, uses: ["splitLine"] }, splitLine: { size: 300, uses: [] }, bigChartHelper: { size: 9000, uses: [] }, }, },}; const kept = new Set();function keep(name) { if (kept.has(name)) return; kept.add(name); modules["utils.js"].exports[name].uses.forEach(keep);}modules["main.js"].imports["utils.js"].forEach(keep); const all = Object.entries(modules["utils.js"].exports);const total = all.reduce((s, [, e]) => s + e.size, 0);const shipped = all.filter(([n]) => kept.has(n)).reduce((s, [, e]) => s + e.size, 0);console.log("kept:", [...kept]);console.log("dropped:", all.map(([n]) => n).filter((n) => !kept.has(n)));console.log(`bytes: ${shipped} of ${total}`);
Output
Press Run (⌘ Enter) to see what happens.

Tree shaking only works when the bundler can prove that dropping code is safe. CommonJS require is dynamic, and a module that does work at the top level (patching a global, say) has side effects, so bundlers keep it. Libraries mark themselves safe with "sideEffects": false in package.json.

The names you will meet: Vite is the default for most new front-end projects; since Vite 8 it uses Rolldown, a Rust bundler compatible with Rollup's plugin API, for both dev and production. esbuild is a very fast Go bundler used inside many tools and for bundling Node services. Turbopack is the Rust bundler in Next.js, the default since Next.js 16. webpack still runs a huge number of older apps; you will maintain it more than you choose it.

Source maps map minified code back to your original files, so a production stack trace points at checkout.ts:42, not index-a8f3.js:1:90211. Generate them for production, but upload them to your error tracker and keep them off the public server if you do not want your source readable, which is what "hidden" source map options are for.

The exports and type fields

Two package.json fields decide how your package is loaded. "type": "module" makes .js files ES modules, as in the Node.js lesson. exports defines the package's public entry points, and blocks everything else:

node_modules/acme-utils/package.json
{
  "name": "acme-utils",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    },
    "./money": "./dist/money.js",
    "./package.json": "./package.json"
  }
}

Conditions are checked in order, and types goes first so TypeScript finds the declarations.

Predict the outputJavaScript

What does this print?

// dist/index.js exports who = "esm"; dist/index.cjs sets who = "cjs"
const a = require("acme-utils");
console.log(a.who);

import("acme-utils")
.then((b) => console.log(b.who))
.then(() => import("acme-utils/dist/internal/secret.js"))
.catch((e) => console.log(e.code));
Need a nudge? Hints walk you through it.

For scripts, stick to conventions so anyone can work in the repo without reading docs: dev, build, start, test, lint, format, typecheck. CI should call the same scripts developers do.

Match the pairs0/6 matched

Match each tool to its job.

Choose an item, then its match on the other side.
Key terms
lockfile
The file that records the exact version, source and integrity hash of every installed package.
phantom dependency
A package your code imports that is not in your package.json and only works because hoisting put it there.
peerDependencies
Packages a library needs but expects the host app to provide, so only one copy is installed.
typosquatting
Publishing a malicious package with a name close to a popular one, waiting for a typo.
provenance
A signed statement linking a published package version to the repo and CI run that built it.
flat config
ESLint's eslint.config.js format: one file exporting an array of config objects.
tree shaking
Removing exports that nothing imports, possible because ES module imports are static.