Starting a project 10
| Command | What it does |
|---|---|
npm init | Create package.json step by stepWith no initializer npm asks its questions in the terminal and then writes the file. |
npm init -y | Create package.json with defaultsSkips every question and takes the default answers. |
npm init INITIALIZER | Scaffold from a create packageUses the package named create-INITIALIZER and runs its main bin, so react-app runs create-react-app. |
npm init --scope=@foo --yes | Create a scoped packageNames the new package inside that scope, as in @foo/whatever, and accepts all defaults. |
npm init --init-private -y | Create a private packageWrites the private field as true into the generated package.json. |
npm pkg get name | Read a package.json fieldPrints the value of that key; several keys can be listed and dots reach nested fields. |
npm pkg set description='Awesome package' engines.node='>=10' | Set package.json fieldsWrites each key=value pair into package.json; a dotted key creates or changes a nested property. |
npm pkg set private=true --json | Set a field as JSONParses the value before saving, so true is stored as a boolean rather than a string. |
npm pkg delete scripts.build | Delete a package.json fieldRemoves the build entry from scripts; any key is addressed with the same dotted syntax. |
npm pkg fix | Repair package.jsonCorrects common mistakes in the file, the clean-up npm otherwise applies when publishing. |
Installing and removing 32
Every flag is a config setting: --foo bar on the command line sets foo to "bar", and a flag given without a value is set to true. npm's pages also write the value after an equals sign, as in --omit=dev.
| Command | What it does |
|---|---|
npm install | Install all project dependenciesWith no arguments it reads package.json and puts every listed dependency into node_modules. |
npm install PACKAGE | Add a dependencyInstalls the package with everything it depends on and records it under dependencies. |
npm install PACKAGE --save-dev | Add a development dependencyRecords the package under devDependencies; -D is the short form. |
npm install PACKAGE --save-optional | Add an optional dependencyRecords it under optionalDependencies; -O is the short form. |
npm install PACKAGE --save-peer | Add a peer dependencyRecords it under peerDependencies instead of dependencies. |
npm install PACKAGE --save-exact | Save an exact versionPins the saved entry to one version number instead of a range; -E is the short form. |
npm install PACKAGE --no-save | Install without savingPuts the package in node_modules but leaves the dependencies list in package.json alone. |
npm install -g PACKAGE | Install a package globallyPuts the package in the global prefix folder and links its commands into the prefix's bin directory. |
npm install sax@latest | Install a tagged versionTakes whichever version the registry holds under that tag and fails when the tag is missing. |
npm install [email protected] | Install an exact versionFails when that version was never published to the registry. |
npm install sax@">=0.1.0 <0.2.0" | Install within a version rangeThe range goes in quotes so the shell hands it to npm as one argument. |
npm install my-react@npm:react | Install under an aliasLets two versions of one package sit side by side, or gives a long name a shorter import name. |
npm install ./package.tgz | Install from a tarball fileThe file must end in .tar, .tar.gz or .tgz and hold a package.json with a name and a version. |
npm install ./sub-package | Install from a local folderA folder inside the project gets its own dependencies installed; one outside the project root is only symlinked. |
npm install github:mygithubuser/myproject | Install from a GitHub repositoryClones the repository with git; npm 12 refuses git dependencies unless the allow-git setting permits them. |
npm install --allow-git all | Allow git dependenciesLifts npm 12's default block on git sources for this run; root permits only those named in the project's package.json. |
npm install sax --force | Force a fresh downloadFetches remote resources again even when a copy already sits on disk; -f is the short form. |
npm install --prefix /path/to/dir | Install in another directoryRuns the command against that folder while the shell stays where it is. |
npm ci | Clean install from the lockfileRequires package-lock.json, deletes an existing node_modules first and stops when the lock and package.json disagree. |
npm ci --omit dev | Clean install without devDependenciesKeeps development packages off disk, although they are still resolved and stay in the lockfile. |
npm install-test | Install, then run testsTakes the same arguments as an install and runs the test script straight afterwards; the two letters "it" are its alias. |
npm install-ci-test | Clean install, then run testsChains a lockfile install and the test script in one command; cit is the short alias. |
npm uninstall PACKAGE | Remove a dependencyDeletes the package and takes it out of package.json and the lockfile; remove, rm and un are aliases. |
npm uninstall lodash --no-save | Remove but keep the entryTakes the files out of node_modules while package.json and the lockfile stay as they were. |
npm uninstall -g PACKAGE | Remove a global packageWorks on the global prefix folder rather than the current project. |
npm link | Register a global linkRun inside the package being developed; it symlinks that folder into the global packages folder. |
npm link PACKAGE-NAME | Link a package into a projectSymlinks the registered package into this project's node_modules; the name comes from its package.json, not its folder. |
npm link ../node-redis | Link a folder in one stepDoes both steps at once: registers that directory globally and links it into the current project. |
npm dedupe | Flatten duplicated dependenciesMoves shared dependencies further up the tree without installing anything new; ddp is the alias. |
npm find-dupes | Preview what dedupe would changeRuns the dedupe command as a dry run: it reports the duplicates and leaves the package tree untouched. |
npm prune | Delete unlisted packagesClears out of node_modules whatever is not on any package's dependency list. |
npm prune --omit=dev | Strip development packagesAlso removes what devDependencies lists; setting NODE_ENV to production has the same effect. |
Install scripts and patches 14
Since npm 12 the install scripts of dependencies do not run until they are approved; after approving, npm rebuild runs the newly allowed scripts.
| Command | What it does |
|---|---|
npm install-scripts ls | List scripts awaiting reviewRead-only: shows each dependency whose install scripts the allowScripts field does not cover yet. |
npm approve-scripts canvas sharp | Approve named packagesAdds them to allowScripts in package.json, pinned to the version installed now. |
npm approve-scripts --all | Approve every pending scriptMeant for after a review: allows all packages whose install scripts are still unreviewed. |
npm approve-scripts --no-allow-scripts-pin canvas | Approve any version of a packageWrites a name-only entry, so later versions of the package keep their approval. |
npm approve-scripts --allow-scripts-pending | Preview unapproved scriptsLists the packages that still need a decision and leaves package.json unchanged. |
npm deny-scripts telemetry-pkg | Block a package from running scriptsStores an explicit false entry that a later blanket approval does not override. |
npm deny-scripts --all | Deny every pending scriptMarks all packages with unreviewed install scripts as denied; ones already approved keep their entry. |
npm install-scripts prune --dry-run | Preview stale approvalsShows which allowScripts entries would go, without removing them. |
npm install-scripts prune | Drop stale script approvalsCleans out approvals for packages that are gone or no longer carry an install script. |
npm rebuild | Rebuild installed packagesRuns the install lifecycle scripts again and relinks bins, for example after changing the Node.js version; rb is the alias. |
npm patch PKG | Start patching a dependencyShort for patch add: unpacks a fresh copy of the package into a temporary folder and prints the path to edit. |
npm patch commit EDIT-DIR | Save edits as a patchWrites the diff to the patches folder, registers it under patchedDependencies and updates the lockfile. |
npm patch ls | List registered patchesAlso shows how many installed copies each patch applies to. |
npm patch rm PKG | Remove a patchUnregisters the package's patches and deletes a patch file once nothing else refers to it. |
Updating and auditing 16
| Command | What it does |
|---|---|
npm outdated | List outdated dependenciesAsks the registry whether newer versions exist for what the project depends on directly. |
npm outdated --all | Include nested dependenciesExtends the report from direct dependencies to every outdated package deeper in the tree. |
npm outdated --global | Check global packagesWith no package.json range to compare against, the wanted column simply repeats the latest version. |
npm update | Update within semver rangesMoves packages to the newest versions their ranges allow and installs missing ones; the ranges in package.json stay as written. |
npm update PACKAGE | Update one packageLimits the update to the packages named; up and upgrade are aliases. |
npm update --save | Update and rewrite package.jsonAlso raises the version ranges written in package.json to match what was installed. |
npm update -g | Update global packagesApplies the update to every globally installed package that is out of date. |
npm audit | Scan for known vulnerabilitiesReports the findings without changing anything and exits non-zero when any are found. |
npm audit fix | Install compatible security fixesApplies the updates that stay inside the declared dependency ranges. |
npm audit fix --force | Apply breaking security fixesAlso moves top-level dependencies across major versions, which the plain fix leaves alone. |
npm audit fix --dry-run --json | Preview fixes as JSONShows what the fix would do, with the install details in JSON, and changes nothing. |
npm audit fix --package-lock-only | Fix the lockfile onlyUpdates package-lock.json and leaves node_modules as it is. |
npm audit --json | Audit report as JSONPrints the full report in machine-readable form for other tools. |
npm audit --audit-level=moderate | Fail only from a severity levelSets the threshold for a failing exit code; lower severities still appear in the printed report. |
npm audit signatures | Verify registry signaturesChecks the signatures and the provenance attestations of the downloaded packages. |
npm sbom --sbom-format cyclonedx | Generate an SBOMLists the project's dependencies as a CycloneDX document; spdx is the other accepted format. |
Running scripts 14
npx and npm exec read their arguments differently: npx wants its own options before the package name, while npm exec uses a double dash to mark where its options end.
| Command | What it does |
|---|---|
npm run SCRIPT | Run a package.json scriptRuns the named entry of the scripts object with node_modules/.bin added to the PATH; run-script is the long name. |
npm run | List available scriptsWith no name it prints the scripts, lifecycle ones separately from the directly-run ones. |
npm run test -- --grep="pattern" | Pass flags through to a scriptEverything after the double dash goes to the script untouched instead of being read by npm. |
npm run env | List script environment variablesBuilt-in script that prints the variables a script will see, unless the package defines its own env. |
npm test | Run the test scriptShorthand for the test entry in scripts; t and tst are aliases. |
npm start | Run the start scriptFalls back to node server.js when scripts has no start entry. |
npm stop | Run the stop scriptHas no fallback: nothing runs unless the scripts object defines stop. |
npm restart | Restart the packageRuns the restart script, or stop followed by start with their pre and post hooks when none is defined. |
npm exec -- tap --bail test/foo.js | Run a local package binaryUses the copy of tap already in the project's dependencies and hands it the remaining arguments; x is the alias. |
npx tap --bail test/foo.js | Run a binary with npxThe same call through npx, which needs no double dash because its own options must come before the package name. |
npm exec --package=foo -- bar --bar-argument | Run a differently named binaryTakes the bar command from the foo package when the command name does not match the package name. |
npx -c 'eslint && say "hooray, lint passed"' | Run a shell command lineExecutes the quoted string as a shell script inside the current project's context. |
npx create-react-app my-app --template typescript | Run a package without installing itArguments after the package name go to that program, not to npx; a missing package is fetched into the npm cache. |
npx --yes PACKAGE | Skip the npx install promptAnswers the question npx asks before it downloads a package that is not installed; -y is the short form. |
Inspecting packages 27
| Command | What it does |
|---|---|
npm ls | Show the dependency treePrints only the project's immediate dependencies unless a depth or --all is given; list is the alias. |
npm ls --all | Show the full dependency treeAdds the dependencies of dependencies, down to every level. |
npm ls promzard | Find where a package is usedNarrows the tree to the paths that lead to the named package. |
npm ls --depth DEPTH | Limit the tree depthSets how many levels below the direct dependencies are drawn; 0 is the default. |
npm ls --global | List global packagesLists what is installed globally rather than in the current project. |
npm ls --json | Output the tree as JSONPrints JSON data in place of the drawn tree. |
npm ll | List with extended detailsBehaves like ls with the long format switched on; la does the same. |
npm explain PACKAGE | Explain why a package is installedPrints the dependency chain that pulled the package into the project; why is the alias. |
npm query SELECTOR | Query dependencies with a selectorTakes a CSS-style selector and returns the matching dependencies as an array of objects. |
npm view PACKAGE | Show registry data for a packagePrints the metadata of the latest version unless another is named; info and show are aliases. |
npm view connect versions | List published versionsPrints the package's whole version history from the registry. |
npm view [email protected] dependencies | Show one field of a versionField names after the package limit the output, here to what that release depends on. |
npm view npm repository.url | Read a nested fieldA period steps into child fields, here the git address inside the repository entry. |
npm view express "dist-tags.latest" | Show the latest tagged versionReturns the version number the latest tag currently points to. |
npm search TERM | Search the registryMatches the terms against package metadata; find, s and se are aliases. |
npm docs PKGNAME | Open a package's documentationGuesses the documentation URL and opens it in the browser; home is the alias. |
npm repo PKGNAME | Open a package's repositoryOpens the repository page in the browser; without a name it uses the package.json of the current folder. |
npm bugs PKGNAME | Open a package's issue trackerOpens the bug tracker URL or the support mail address; issues is the alias. |
npm fund | List funding informationDraws a tree of the dependencies that seek funding, each with its funding type and link. |
npm root | Print the node_modules pathWrites the effective folder to standard output, which suits shell scripts. |
npm root --global | Print the global node_modules pathGives the folder where globally installed packages live. |
npm prefix | Print the project rootShows the nearest parent directory that holds a package.json or a node_modules folder. |
npm prefix -g | Print the global prefix |
npm diff | Compare with the published versionIn a package folder it diffs the local files against the tarball tagged latest in the registry. |
npm diff [email protected] [email protected] | Compare two published versionsPrints a git-style patch of the files that differ between the two registry versions. |
npm explore some-dependency -- git pull origin master | Run a command inside a dependencyStarts a subshell in the installed package's folder, runs the command there and ends the subshell straight away. |
npm edit connect | Open a dependency in your editorBrings up the package's folder in the configured editor and rebuilds the package afterwards. |
Configuration 13
| Command | What it does |
|---|---|
npm config list | Show current settingsLists the settings in effect; add --json for JSON output. |
npm config ls -l | Show settings with defaultsAdds npm's internal default values to the list. |
npm config get KEY | Read a settingEchoes the value to stdout; with several keys each value is prefixed by its name. |
npm config get registry | Show the registry in usePrints the registry URL that installs and the doctor connection check go to. |
npm config set KEY=VALUE | Change a settingWrites to the user config file unless a location is given; the older KEY VALUE spelling still works. |
npm config delete KEY | Remove a settingTakes the key out of every configuration file, not just the user one. |
npm config edit | Edit the config fileOpens the user file in your editor; add --global for the global one. |
npm config edit --global | Edit the global config fileOpens the global npmrc rather than the per-user one. |
npm config fix | Repair invalid config entriesUsually this ties loose authentication settings such as _authToken to the registry they belong to. |
npm get KEY | Read a setting, short formShortcut that behaves exactly like the config get sub-command. |
npm set KEY=VALUE | Change a setting, short formShortcut for the config set sub-command with the same key=value syntax. |
npm COMMAND --KEY=VALUE | Override a setting for one runAny config key can be given as a flag for a single command instead of being stored in the ini file. |
npm completion >> ~/.bashrc | Enable tab completionAppends the completion script to the shell start-up file; use ~/.zshrc for zsh. |
Publishing and versions 34
| Command | What it does |
|---|---|
npm version patch | Bump the patch versionRaises the last number in package.json and the lockfile; a prerelease version only loses its suffix. |
npm version minor | Bump the minor versionIn a git repository the bump is also committed and tagged. |
npm version major | Bump the major version |
npm version NEWVERSION | Set an explicit versionTakes any valid semver string in place of a release keyword. |
npm version prerelease --preid PRERELEASE-ID | Bump a prerelease with an identifierPuts the identifier in front of the prerelease number, giving versions such as 1.2.0-rc.8. |
npm version patch -m "Upgrade to %s for reasons" | Bump with a commit messageThe %s in the message is swapped for the new version number in the version commit. |
npm version patch --no-git-tag-version | Bump without a commit or tagChanges the version in the files only and skips the git commit and tag. |
npm version from-git | Take the version from gitReads the most recent git tag and writes it as the package version. |
npm pack | Build the package tarballWith no argument it packs the current folder into a NAME-VERSION.tgz file in the working directory. |
npm pack --dry-run | Preview the published filesLists what the tarball would contain without creating it. |
npm publish | Publish the current packageUploads what is in the working folder to the registry; a name and version pair can never be used twice. |
npm publish --tag=beta | Publish under another tagLeaves the latest tag where it is, so a plain install does not pick up this release. |
npm publish --access=public | Publish a scoped package publiclyMakes the published package publicly viewable and installable; restricted is the opposite value, meant for scoped packages. |
npm publish --dry-run | Rehearse a publishReports what would be uploaded and makes no change to the registry. |
npm publish --provenance | Publish with provenanceOn a supported cloud CI/CD service the release is publicly tied to the build that produced it. |
npm unpublish PACKAGE | Unpublish from the registrynpm suggests deprecating instead; an unpublished name and version pair cannot be reused. |
npm deprecate my-thing@"< 0.2.3" "critical bug fixed in v0.2.3" | Deprecate a version rangeEveryone who installs a matching version sees the message as a warning. |
npm undeprecate PACKAGE | Lift a deprecationClears the warnings a deprecate call attached to the package. |
npm dist-tag ls PACKAGE | List a package's tagsShows every distribution tag and its version; with no name it uses the package in the current folder. |
npm dist-tag add PACKAGE TAG | Point a tag at a versionThe package argument must carry the version, as in [email protected]; dist-tags is the alias. |
npm dist-tag rm PACKAGE TAG | Remove a tagFor tags that are no longer needed; with two-factor writes enabled it asks for a one-time password. |
npm access get status | Show a package's access levelActs on the package in the current directory when no name is passed. |
npm access set status=public | Make a package publicChanges the access level of a package that is already published to public. |
npm access list collaborators | List a package's collaborators |
npm owner ls PACKAGE | List package ownersShows the users who may modify the package and push new versions; author is the alias. |
npm owner add USER PACKAGE | Add a package ownerThe new maintainer can change metadata, publish versions and add further owners. |
npm owner rm USER PACKAGE | Remove a package ownerTheir rights over the package end immediately. |
npm stage publish | Stage a release for approvalUploads the packed package in a state that stays unavailable to the public until a maintainer approves it. |
npm stage list | List staged versions |
npm stage approve STAGE-ID | Approve a staged releasePrompts for two-factor authentication and then publishes the staged package. |
npm stage reject STAGE-ID | Reject a staged releaseAsks for 2FA and permanently removes the staged package. |
npm trust github PACKAGE --file FILE --repo OWNER/REPO --allow-publish | Trust a GitHub Actions workflowCreates the trusted-publisher link between the package and one workflow file; at least one allow flag is required. |
npm trust list PACKAGE | List trusted publishersShows the existing configuration together with the ID that revoking needs. |
npm trust revoke --id ID PACKAGE | Revoke a trusted publisherNeeded before a new one can be created, since a package holds only one configuration. |
Account, orgs and teams 20
npm 12 removed npm adduser: accounts are created on the npm website and npm login signs in. The star, stars and unstar commands went in the same release.
| Command | What it does |
|---|---|
npm login | Log in to the registryVerifies the user and stores the credentials in the .npmrc file. |
npm login --scope=@mycorp --registry=https://registry.mycorp.com | Log in to a private registryAlso maps the scope to that registry for later installs of @mycorp packages. |
npm logout | End the registry sessionOn token-based registries the token stops working everywhere it is used, not only on this machine. |
npm logout --scope=@mycorp | Log out of a scoped registryRemoves the scope's link to its registry together with the stored token. |
npm whoami | Show the logged-in userPrints the username that belongs to the current token or credentials. |
npm profile get | Show your registry profileLists every profile property, or only the ones named after it. |
npm profile set PROPERTY VALUE | Change a profile propertyWorks for email, fullname, homepage and github; the password has its own interactive form. |
npm profile enable-2fa auth-and-writes | Turn on two-factor authenticationAsks for a one-time password at login and also for publishing and access changes; auth-only covers logins alone. |
npm profile disable-2fa | Turn off two-factor authentication |
npm token list | List access tokensTokens appear abbreviated; the full value is never shown. |
npm token create | Create an access tokenAsks for your password, and for a one-time password when two-factor authentication is on. |
npm token revoke ID | Revoke an access tokenAccepts the full token or a shortened id and removes it from the registry at once. |
npm org set my-org @mx-smith | Add a user to an orgWithout a role the user joins as a developer. |
npm org set my-org @mx-santos admin | Give an org member a roleAdds the user as admin or promotes an existing developer; owner is the third role. |
npm org rm my-org mx-santos | Remove an org member |
npm org ls my-org | List org membersAdd a username to see just that person's role, or --json for JSON output. |
npm team create @org:newteam | Create a teamA team is always written as the org scope and the team name joined by a colon. |
npm team add @org:newteam username | Add a user to a team |
npm team rm @org:newteam username | Remove a user from a team |
npm team ls @org | List an org's teamsGiven a team such as @org:newteam instead, it lists that team's members. |
Workspaces 15
| Command | What it does |
|---|---|
npm init -w ./packages/a | Create a workspaceMakes the folder and its package.json and adds it to the workspaces list of the root package.json. |
npm install abbrev -w a | Add a dependency to one workspaceSaves the package in workspace a's package.json rather than in the root project. |
npm install b -w a | Depend on a sibling workspacenpm notices that b is a workspace, links it locally and downloads nothing. |
npm run test --workspace=a | Run a script in one workspaceSame as changing into packages/a and running the script there. |
npm run test --workspace=a --workspace=b | Run a script in several workspacesThe flag may be repeated, once for each workspace to target. |
npm run test --workspace=packages | Run in a folder's workspacesA parent directory selects all the workspaces inside it. |
npm run test --workspaces | Run a script in all workspacesGoes through every configured workspace in the order package.json lists them. |
npm run test --workspaces --if-present | Skip workspaces without the scriptA workspace that does not define the script is passed over instead of failing the run. |
npm run SCRIPT --workspaces --include-workspace-root | Include the root project tooAdds the root package to the run alongside the workspaces; --iwr is the shorthand. |
npm test -w a -w b | Run tests in chosen workspaces-w is the short form of --workspace and can be repeated as well. |
npm exec --ws -- eslint ./*.js | Run a command in every workspace--ws is short for --workspaces; here eslint runs once inside each workspace folder. |
npm exec --workspace=a -- eslint ./*.js | Run a command in one workspaceThe workspace is given by its name or by the path of its directory. |
npm publish --workspaces | Publish all workspaces |
npm pkg set funding=https://example.com --ws | Set a field in every workspaceWrites the same value into the package.json of each configured workspace. |
npm fund -w a | Funding info for one workspaceFilters the list down to that workspace and what it depends on. |
Cache and troubleshooting 14
| Command | What it does |
|---|---|
npm -v | Show the npm version |
npm install -g npm@latest | Upgrade npm itselfOn Linux or macOS it may need sudo, depending on how Node was installed. |
npm doctor | Check the npm environmentTests registry access, the Node and git executables, folder permissions and the cache, then lists recommended changes. |
npm doctor connection | Run a single doctor checkNames from the synopsis, such as registry, versions, permissions or cache, limit the run to those checks. |
npm ping | Test the registry connectionContacts the configured registry, checks authentication and prints the response time. |
npm cache verify | Verify the cacheChecks the integrity of the cached data offline and garbage-collects what is no longer needed. |
npm cache clean --force | Clear the cachenpm calls this unnecessary except to reclaim disk space, which is why it insists on the flag. |
npm cache ls | List cache entriesTakes an optional name@version to narrow the list. |
npm cache npx ls | List the npx cacheCovers the separate folder where npm exec keeps packages fetched for one-off commands. |
npm cache npx rm | Clear the npx cacheRemoves the keys named after it, or every entry when none is given. |
npm help TERM | Open help for a topicShows the documentation page of a known topic and otherwise falls back to a help search. |
npm help-search TEXT | Search the npm documentationLists the matching help pages by relevance and opens the page directly when only one matches. |
npm COMMAND -h | Show a command's usagePrints the usage line and the options that one command accepts. |
npm -l | Show usage for all commands |
No row on this page matches that filter.
Notes
Installing
npm init -y writes a package.json with defaults so a folder becomes a project. npm install PACKAGE adds a package to dependencies and npm install PACKAGE --save-dev to devDependencies — build tools, test runners and linters belong in the second, because an install with --omit=dev leaves them off disk. Plain npm install with no name installs everything in package.json, and npm ci installs from the lockfile exactly and never rewrites it, which is what npm intends for CI and deployment. npm uninstall PACKAGE removes a package and its entry; npm update moves packages to the newest versions the ranges allow and leaves the ranges in package.json as written unless --save is added.
Running
npm run SCRIPT runs a script from the scripts section with node_modules/.bin on the PATH, which is why npm run build finds a locally installed bundler. npm start and npm test are shorthands for the start and test scripts. npx runs a package binary — from the project's dependencies if present, otherwise fetched into the npm cache after a prompt — so one-off tools like npx create-react-app my-app --template typescript never need a global install.
Seeing what is installed
npm ls prints the direct dependencies and their versions, npm ls --all the whole tree, and npm outdated shows which have newer releases. Commit package-lock.json: it is what makes npm ci on another machine produce the same node_modules.
What changed in npm 12
Install scripts of dependencies are blocked until approved: npm install-scripts ls shows what is waiting, npm approve-scripts --all approves after a review, and npm rebuild then runs the newly allowed scripts. Git dependencies are refused unless allow-git is set, npm adduser, npm shrinkwrap and the star commands are gone, and unknown or abbreviated flags are an error instead of a warning. This page follows npm 12.2.0; npm -v shows which version is installed.
Questions
What is the difference between npm install and npm ci?
npm install compares package.json with package-lock.json, uses the locked versions when they satisfy the ranges and otherwise resolves new ones and updates the lockfile. npm ci needs an existing lockfile, stops with an error when it does not match package.json, removes node_modules before installing and never writes to either file.
How do I pass arguments to an npm script?
Put them after a double dash: npm run test -- --grep="pattern". Positional arguments reach the script anyway; the double dash is for options that start with a hyphen, which npm would otherwise read itself. They go only to the named script, not to its pre or post scripts.
Why did a package's install script not run after moving to npm 12?
npm 12 blocks the install scripts of dependencies by default. npm install-scripts ls lists the packages waiting for review, npm approve-scripts canvas sharp or npm approve-scripts --all records the approval in the allowScripts field of package.json, and npm rebuild runs the scripts that are now allowed.
What is the difference between npx and npm exec?
npx is built on npm exec, with one difference in how arguments are read. With npx every option meant for npx has to come before the package name, and whatever follows goes to the program. With npm exec a double dash marks where npm's options end, as in npm exec -- tap --bail test/foo.js.
Which commands did npm 12 remove?
npm adduser, npm shrinkwrap, npm star, npm stars and npm unstar. Accounts are created on the npm website and npm login signs in; a project-root npm-shrinkwrap.json should be renamed to package-lock.json.
Does this page cover yarn?
No. Every row comes from the npm documentation for npm 12.2.0; yarn and pnpm have their own commands and are not listed.
Sources and checks
- npm Docs (CLI v12) — npm init Creating a package.json, initializers, scopes
- npm Docs (CLI v12) — npm pkg Reading and editing package.json fields
- npm Docs (CLI v12) — npm install Package specs, save flags, forced downloads
- npm CLI 12.2.0 source — built-in help text of every command (docs.js.test.cjs snapshot) Usage lines, option lists and aliases as npm prints them with -h
- npm Docs (CLI v12) — config Command-line flags, shorthands and default settings
- npm Docs (CLI v12) — npm ci Clean installs from the lockfile
61 more source pages
- npm Docs (CLI v12) — npm uninstall Removing packages
- npm Docs (CLI v12) — npm link Linking a package folder
- npm Docs (CLI v12) — npm dedupe Deduplicating the tree, find-dupes
- npm Docs (CLI v12) — npm prune Removing extraneous packages
- npm Docs (CLI v12) — npm install-scripts Reviewing and pruning install-script approvals
- npm Docs (CLI v12) — npm approve-scripts Approving install scripts
- npm Docs (CLI v12) — npm deny-scripts Denying install scripts
- npm Docs (CLI v12) — npm rebuild Rebuilding packages
- npm Docs (CLI v12) — npm patch Patching installed dependencies
- npm Docs (CLI v12) — npm outdated Outdated report
- npm Docs (CLI v12) — npm update Updating packages
- npm Docs (CLI v12) — npm audit Security audit, fixes and signatures
- npm Docs (CLI v12) — npm run Running scripts, passing arguments, workspace filters
- npm Docs (CLI v12) — npm test Test script
- npm Docs (CLI v12) — npm start Start script
- npm Docs (CLI v12) — npm stop Stop script
- npm Docs (CLI v12) — npm restart Restart script
- npm Docs (CLI v12) — npm exec npm exec and npx examples, workspace runs
- npm Docs (CLI v12) — npx Running a package with npx
- npm Docs (CLI v12) — npm ls Listing the dependency tree
- npm Docs (CLI v12) — npm explain Why a package is installed
- npm Docs (CLI v12) — npm query Dependency selector queries
- npm Docs (CLI v12) — npm view Registry data and field access
- npm Docs (CLI v12) — npm search Searching the registry
- npm Docs (CLI v12) — npm docs Opening package documentation
- npm Docs (CLI v12) — npm repo Opening a repository page
- npm Docs (CLI v12) — npm bugs Opening a bug tracker
- npm Docs (CLI v12) — npm fund Funding information
- npm Docs (CLI v12) — npm root node_modules path
- npm Docs (CLI v12) — npm prefix Local and global prefix
- npm Docs (CLI v12) — npm diff Comparing package versions
- npm Docs (CLI v12) — npm explore Subshell in a package folder
- npm Docs (CLI v12) — npm edit Editing an installed package
- npm Docs (CLI v12) — npm config config sub-commands, npm get and npm set
- npm Docs (CLI v12) — npm doctor Environment checks
- npm Docs (CLI v12) — npm completion Shell tab completion
- npm Docs (CLI v12) — npm version Version bumps, commit message, from-git
- npm Docs (CLI v12) — npm pack Creating a tarball
- npm Docs (CLI v12) — npm publish Publishing, files included, workspace publishing
- npm Docs (CLI v12) — npm dist-tag Distribution tags, publishing under a tag
- npm Docs (CLI v12) — npm access Package access level and team grants
- npm Docs (CLI v12) — npm unpublish Unpublishing
- npm Docs (CLI v12) — npm deprecate Deprecating versions
- npm Docs (CLI v12) — npm undeprecate Removing deprecation warnings
- npm Docs (CLI v12) — npm owner Package owners
- npm Docs (CLI v12) — npm stage Staged publishing
- npm Docs (CLI v12) — npm trust Trusted publishing configurations
- npm Docs (CLI v12) — npm login Logging in, scoped registries
- npm Docs (CLI v12) — npm logout Logging out
- npm Docs (CLI v12) — npm whoami Current user
- npm Docs (CLI v12) — npm profile Profile settings and two-factor authentication
- npm Docs (CLI v12) — npm token Access tokens
- npm Docs (CLI v12) — npm org Organization members and roles
- npm Docs (CLI v12) — npm team Teams and team membership
- npm Docs (CLI v12) — workspaces Creating workspaces and running commands in them
- npm Docs — Try the latest stable version of npm Checking and upgrading npm itself
- npm Docs (CLI v12) — npm ping Registry ping
- npm Docs (CLI v12) — npm cache Cache and npx cache sub-commands
- npm Docs (CLI v12) — npm help Help topics
- npm Docs (CLI v12) — npm help-search Searching the help
- npm CLI 12.2.0 — CHANGELOG.md Breaking changes of npm 12: removed commands, install scripts blocked by default
Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.
6 rows from the earlier version of this page were removed in that check: duplicates, and bindings the documentation does not list or lists differently.
Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.