skip to content

npm

npm reads package.json, writes package-lock.json and a hoisted node_modules tree, runs lifecycle scripts and publishes packages. Most JavaScript interviews ask what an install actually produces.

on this pageshow

explore

questions

28

With npm, why does `npm ci` in a CI job fail right after a teammate adds a dependency to `package.json`, and what fixes it?

level: juniorimportance: must knowfreq 40%

answer

  1. a frozen install never writes
  2. two files must agree
  3. the 'in sync' usage error
  4. Missing: name@version from lock file
  5. which command rewrites the lock

basics

~20 s

npm ci installs exactly what package-lock.json records and never writes it, so when package.json declares a dependency the lock lacks it exits with an out-of-sync error. Run npm install locally and commit the updated lock.

solid answer

~40 s

`npm ci` is npm's clean install for automated environments. It requires an existing `package-lock.json`, builds the tree `package.json` asks for, compares it with the lock, and on any difference exits with "`npm ci` can only install packages when your package.json and package-lock.json are in sync", listing each `Missing:` or `Invalid:` entry. It never writes `package.json` or the lock, so it cannot repair the drift itself. The teammate either edited the manifest by hand or ran `npm install` and committed only `package.json`. The fix is to run `npm install` locally, which resolves the new dependency and updates `package-lock.json`, then commit both files together. `npm install` is the command that changes dependencies; `npm ci` reproduces them.

code

bash · 5 lines
bash
npm ci                       # fails: package.json and package-lock.json are not in sync
npm install                  # resolves chrono-fmt and rewrites package-lock.json
git add package.json package-lock.json
git commit -m "Record chrono-fmt in the lockfile"
npm ci                       # now passes, and so will the CI job

go deeper

for a junior

Recall the one-line difference: npm install changes the tree and the lock, npm ci reproduces the lock exactly and stops when the two files disagree. The fix is a local npm install plus committing the lock.

for a middle

Explain what npm ci checks: it builds the tree package.json asks for, compares it with the lock, and only then empties node_modules. Read the Missing and Invalid lines to name the drifted dependency.

for a senior

Treat the failure as the gate working, not a flaky job. Push for package.json and package-lock.json to change together in one commit, and reject pull requests where only one of them moved.

for a principal

Frame the lock as a reviewed artifact: a pipeline that reproduces it exactly costs a little friction per dependency change and buys installs that never differ between machines.

## What `npm ci` checks before it touches anything `npm ci` is npm's **clean install**, meant for test platforms, continuous integration and deployments. It is not a faster `npm install`; it is a different contract. Before it removes or downloads anything, it works through three steps in order: 1. **Load `package-lock.json`.** With no lockfile it stops at once with a usage error: it "can only install with an existing package-lock.json", and you are told to run an install first. 2. **Build the tree `package.json` asks for** under the current configuration, and compare that tree entry by entry with the one the lock records. 3. **Refuse on any difference.** The headline is "`npm ci` can only install packages when your package.json and package-lock.json are in sync. Please update your lock file with `npm install` before continuing.", followed by one line per mismatch: `Missing: [email protected] from lock file` for a dependency the lock has never heard of, or `Invalid: lock file's [email protected] does not satisfy [email protected]` when a range moved past the locked version. Only when the lock validates does `npm ci` empty the `node_modules` folders (the root's and each workspace's) and install exactly the versions the lock lists. A failed validation therefore leaves the runner's existing folder untouched. ## Why it refuses instead of fixing - **It never writes `package.json` or `package-lock.json`.** npm describes the install as essentially frozen, so there is no code path that could add the missing entry. - **It installs whole projects only.** Individual dependencies cannot be added with `npm ci`; that is what `npm install <name>` is for. - **The mismatch is information.** It means the commit is incomplete: the manifest gained a dependency whose resolved version, tarball URL and integrity hash were never recorded and reviewed. - **A silent repair would hide the problem.** A runner that re-resolved on its own would install whatever version the registry served that minute and write a lock onto a machine that is thrown away after the job. ## `npm install` versus `npm ci` | | `npm install` (no arguments) | `npm ci` | |---|---|---| | Needs a lockfile | No; it creates one | Yes; errors without one | | Lock disagrees with `package.json` | `package.json` wins: npm resolves and updates the lock | Exits with the out-of-sync error | | Writes `package.json` / lock | Yes, by default | Never | | Existing `node_modules` | Reused and updated in place | Emptied after the lock validates | | Add one package | Yes, `npm install chrono-fmt` | No, whole project only | | Where it belongs | A developer machine, when dependencies change | CI, test and deployment | When the lock's versions still satisfy every range, `npm install` uses them exactly, so on an unchanged project both commands produce the same tree. They differ only in what they do when the two files disagree. ## Repairing the drift 1. Check out the branch whose CI run failed. 2. Run `npm install` with no arguments. npm compares `package.json` with the lock, resolves the new dependency within its declared range, and writes the new `packages` entries into `package-lock.json`. 3. Look at the lock diff: the new dependency, plus anything it pulls in, each with a `version`, `resolved` URL and `integrity` hash. 4. Commit `package.json` and `package-lock.json` together. 5. Optionally run `npm ci` locally; it should now pass, and so will CI. If you only need the lock repaired and not a working `node_modules`, `npm install --package-lock-only` updates `package-lock.json` without downloading packages. ## Keeping it from coming back - Make it a review rule: a pull request that changes a dependency section of `package.json` and not `package-lock.json` is incomplete. - Do not "fix" the pipeline by switching it to `npm install`; that removes the check and lets every CI run resolve its own tree. - Do not delete the lock to make the error go away; without a lock every range is resolved from scratch. - If the lock was written with flags that change the shape of the tree, `npm ci` needs those same flags, which is why such settings belong in the committed project `.npmrc`. - Run `npm ci` in pull-request checks, not only on the main branch, so an incomplete commit fails where its author is still looking at it. The out-of-sync error is one of the cheapest failures a pipeline can give you: it names the package, it fires before anything is deleted or downloaded, and the fix is one local command and one commit.

  • Why not switch the CI job to `npm install` so it stops failing?
    Because `npm install` would quietly resolve the missing dependency on the runner, at whatever version the registry serves that day, and write a lock nobody commits. CI would then test a tree no developer has, and the next run could pick a different one. The failure is telling you the commit is incomplete; fix the commit, not the command.
  • What does `npm ci` do to an existing `node_modules`, and when?
    It empties every `node_modules` folder, the root's and each workspace's, and installs from scratch, but only after it has loaded the lock and confirmed that it matches `package.json`. An out-of-sync lock fails the job before anything is removed. That is why `npm ci` is slower on a warm laptop but predictable on a fresh runner.
  • Can you update only `package-lock.json`, without downloading into `node_modules`?
    Yes: `npm install --package-lock-only` resolves against `package.json` and writes the lock without checking or populating `node_modules`. It is handy when you only need a correct lock in the commit; `npm ci` will accept the result as long as the two files agree.

  • npm ci updates package-lock.json when it disagrees with package.json.
  • Switching the pipeline back to npm install is the right fix for this error.
  • npm ci can add a single new package, the same way npm install does.
  • npm ci works without a lockfile and simply resolves from package.json.
  • Clearing the runner's node_modules makes the out-of-sync error go away.
open as a page

In an npm project, what is the difference between `dependencies` and `devDependencies`, and what does `npm install --omit=dev` leave out?

level: juniorimportance: must knowfreq 42%

basics

~20 s

In package.json, dependencies are packages the code needs at runtime and install for anyone who installs the package; devDependencies are build and test tools. npm install --omit=dev keeps devDependencies off disk while still recording them in the lockfile.

open as a page

With npm, what does `npm publish` put into a package's tarball by default, and how do you see that file list before publishing?

level: juniorimportance: must knowfreq 24%

basics

~20 s

Without a files field, npm publish packs every file in the package folder except what .npmignore (or .gitignore, when there is no .npmignore) and npm's built-in ignores exclude. Run npm pack --dry-run to print the exact list first.

open as a page

In an npm project, how does `npm run build` run `vite build` when Vite is only a devDependency and not installed globally?

level: juniorimportance: must knowfreq 40%

basics

~20 s

npm links every command a dependency declares in its bin field into node_modules/.bin, and npm run adds that folder to the PATH it gives each script, so vite resolves to the project's own installed copy.

open as a page

In an npm project, what does the root package.json `workspaces` field declare, and what does one `npm install` at the root then produce?

level: juniorimportance: must knowfreq 32%

basics

~20 s

The root workspaces field lists the folders or globs, such as packages/*, that hold sibling packages. One root npm install symlinks each into the root node_modules by name, hoists shared dependencies there and writes a single root package-lock.json.

open as a page

With npm, how should you resolve a Git merge conflict in `package-lock.json` after two branches each added dependencies?

level: middleimportance: must knowfreq 24%

basics

~20 s

Resolve package.json by hand first, then take one side's package-lock.json whole and run npm install, which keeps every locked version that still satisfies the merged ranges and resolves the rest. Commit both files and confirm with npm ci.

open as a page

With npm 7 or later, how does npm treat a component library's `peerDependencies`, and what changes when `peerDependenciesMeta` marks one peer optional?

level: middleimportance: must knowfreq 22%

basics

~20 s

Since npm 7, a library's non-optional peerDependencies are installed automatically, so the app and the library share one copy of the host. A peer marked optional: true in peerDependenciesMeta is not installed; the app adds it when needed.

open as a page

In npm's `.npmrc`, how do you send the `@harbor` scope to a private registry and give npm its token without committing the token?

level: middleimportance: must knowfreq 19%

basics

~10 s

Put @harbor:registry=https://registry.harbor.example/ and //registry.harbor.example/:_authToken=${HARBOR_NPM_TOKEN} in the project .npmrc. npm expands the environment variable when it reads the file, so only the placeholder is committed.

open as a page

With npm, a design-token package compiles tokens in `prepublishOnly`, yet `npm pack` yields a tarball without them — why, and which hook should build them?

level: middleimportance: must knowfreq 18%

basics

~20 s

prepublishOnly runs only on npm publish; npm pack runs prepack, prepare and postpack. Build in prepack to compile only when a tarball is made, or in prepare to also build on every bare local npm install.

open as a page

With npm, if package.json defines `pretest`, `test` and `posttest`, what does `npm test -- --coverage` run, and which script receives `--coverage`?

level: juniorimportance: should knowfreq 24%

basics

~20 s

npm runs pretest, then test with --coverage appended, then posttest, stopping at the first non-zero exit. Arguments after the double dash go only to the main test script, never to its pre or post hooks.

open as a page

With npm, what does `npm audit fix` change in a project, what does it leave alone, and when does `--force` cross a major version?

level: middleimportance: should knowfreq 20%

basics

~20 s

npm audit fix moves vulnerable packages to non-vulnerable versions that the declared ranges already allow. A fix that needs a range change is left alone unless you pass --force, which may install a SemVer-major update of a direct dependency.

open as a page

With npm, why can `npm ls` show two copies of one library at different majors, and what can `npm explain` and `npm dedupe` do about it?

level: middleimportance: should knowfreq 18%

basics

~20 s

npm's default hoisted layout gives each package name one top-level slot; a dependent whose range rejects that copy gets its own nested copy. npm explain shows which chain demands each copy; npm dedupe merges copies only when one version satisfies every range.

open as a page

In an npm package's package.json, what does `engines` do when a consumer's Node.js is outside its range, and what makes npm refuse?

level: middleimportance: should knowfreq 12%

basics

~20 s

The engines field declares the Node.js (and npm) versions a package supports; by default a mismatch only prints a warning and the install continues. Setting engine-strict=true makes npm refuse with EBADENGINE, and --force overrides even that.

open as a page

With npm, `npm outdated` shows Current 2.1.0, Wanted 2.4.3, Latest 3.0.1 for a package; what does each mean, and what does `npm update` change?

level: middleimportance: should knowfreq 26%

basics

~10 s

Current is the installed version, Wanted the highest version satisfying the package.json range, Latest the version tagged latest. npm update installs within the range (2.4.3) and leaves package.json alone unless run with --save.

open as a page

With npm 12, how do you publish `[email protected]` without moving the `latest` dist-tag, and what happens if you leave out `--tag`?

level: middleimportance: should knowfreq 14%

basics

~20 s

Run npm publish --tag beta: the version goes up under the beta dist-tag and latest stays on 2.x. Since npm 11, publishing a prerelease version without --tag (or a publishConfig tag) stops with an error instead of moving latest.

open as a page

In an npm package that nearly published a `.env` and its source maps, how do `files` and `.npmignore` decide what `npm publish` includes?

level: middleimportance: should knowfreq 13%

basics

~20 s

files is an allow-list: only matching paths, plus package.json, README, LICENSE, main and bin, are packed. .npmignore is a deny-list over the rest, and once it exists npm stops reading .gitignore, so a git-ignored .env can ship.

open as a page

With npm, what does `npx` do when the command's package is not installed in the project, and when does it ask before fetching it?

level: middleimportance: should knowfreq 18%

basics

~20 s

npx (npm exec) runs a matching local copy; otherwise it installs the package into a folder in the npm cache and runs its bin. It prompts first, except with --yes or --no, or in CI or without a TTY, where yes is assumed.

open as a page

With npm workspaces, how do you run `test` in every workspace when some lack it, and include the root's own `test`?

level: middleimportance: should knowfreq 17%

basics

~20 s

Run npm run test --workspaces --if-present: npm runs test in each workspace in turn and skips those without the script. Add --include-workspace-root to run the root's test first; on npm 12 the single-hyphen -ws spelling throws.

open as a page

With npm, a lockfile was written by `npm install --legacy-peer-deps` on a laptop and `npm ci` now fails in CI — why, and what is the durable fix?

level: seniorimportance: should knowfreq 12%

basics

~20 s

--legacy-peer-deps changes the tree npm builds, so npm ci without it computes a different tree than the lock records and fails. Commit legacy-peer-deps=true to the project .npmrc, or fix the peer conflict and regenerate the lock without it.

open as a page

With npm 7 or later, an app moves its UI framework to version 5 and `npm install` stops with `ERESOLVE` because a chart library peers on `^4`; what happened, and what do `--legacy-peer-deps` and `--force` change?

level: seniorimportance: should knowfreq 18%

basics

~10 s

The app's viewlib@5 and the library's peer range ^4 must share one copy, which is impossible, so npm stops with ERESOLVE. --legacy-peer-deps ignores every peer; --force accepts the conflict. Neither makes the pair compatible.

open as a page

With npm, why does an `overrides` entry in a published library's package.json do nothing for the apps that install it, and how does an app force a patched transitive version instead?

level: seniorimportance: should knowfreq 16%

basics

~10 s

npm reads overrides only from the root project's package.json; entries in installed dependencies, workspaces included, are ignored. The app adds its own override, such as "xml-tiny-parser": "^2.8.4", in its root manifest and reinstalls.

open as a page

With npm, `[email protected]` went out broken twenty minutes ago — what do `npm unpublish` and the registry's unpublish policy allow, and why must the fix still ship as 2.4.2?

level: seniorimportance: should knowfreq 8%

basics

~20 s

The registry lets npm unpublish [email protected] through only with no public dependents and, unless the package itself is under 72 hours old, under 300 weekly downloads and one owner. 2.4.1 can never be reused, so the fix ships as 2.4.2.

open as a page

After a project moves to npm 12, `npm ci` succeeds but a native image-resizing addon's binary was never built — why, and what exactly fixes it?

level: seniorimportance: should knowfreq 11%

basics

~20 s

Since npm 12, dependency install scripts are skipped unless the root package.json allowScripts field approves them. Run npm install-scripts approve for the addon, npm rebuild it, and commit package.json so npm ci builds it too.

open as a page

In an npm workspaces repo, `@rota/ui` imports `zone-kit` without declaring it; tests pass locally but consumers get Cannot find module, so why, and what catches it earlier?

level: seniorimportance: should knowfreq 13%

basics

~20 s

Hoisting put zone-kit in the root node_modules because a sibling or the root declares it, and Node.js finds it by walking up from packages/ui. Consumers get only declared dependencies. Declare it with npm install zone-kit -w @rota/ui; test under install-strategy=linked.

open as a page

On npm 12, with `min-release-age=7` in the project `.npmrc`, why does `npm audit fix` leave a package vulnerable and exit non-zero?

level: seniorimportance: nice to knowfreq 5%

basics

~20 s

min-release-age=7 lets npm install only versions published more than seven days ago. A patch released yesterday falls inside that window, so npm 12 keeps the vulnerable version, warns that the fix was blocked and exits non-zero.

open as a page

In a project on npm 12, how does `--ignore-scripts` differ from the `allowScripts` policy, and which scripts still run when it is set?

level: seniorimportance: nice to knowfreq 7%

basics

~20 s

allowScripts only governs dependencies' install scripts and leaves the root project's scripts running; --ignore-scripts stops every lifecycle script, root included, and every pre and post hook. A script you name with npm run, npm test, npm start and similar commands still runs.

open as a page

In an npm workspaces repo, `@rota/date-rules` was bumped to 2.0.0 while `@rota/ui` still declares `^1.0.0`; why does `npm install` now fail with E404?

level: seniorimportance: nice to knowfreq 7%

basics

~20 s

npm links a sibling workspace only when its local version satisfies the dependent's range. 2.0.0 is outside ^1.0.0, so npm asks the registry for @rota/date-rules, which was never published. Re-save the range with npm install @rota/date-rules -w @rota/ui.

open as a page