npm commands

npm command lines from the reference for npm 12.2.0, the release its documentation marks as latest, grouped by task from starting a project to publishing and troubleshooting. Words in capitals such as PACKAGE or SCRIPT are placeholders; names like sax, my-org or packages/a come from npm's own examples. npm 12 no longer runs the install scripts of dependencies until they are approved, and it dropped adduser, shrinkwrap and the star commands. yarn and pnpm commands are not listed here.

209 commands in 11 sections. Checked row by row against npm Docs (CLI v12) on . Edited by Jay.

Starting a project 10

CommandWhat it does
npm initCreate package.json step by stepWith no initializer npm asks its questions in the terminal and then writes the file.
npm init -yCreate package.json with defaultsSkips every question and takes the default answers.
npm init INITIALIZERScaffold 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 --yesCreate a scoped packageNames the new package inside that scope, as in @foo/whatever, and accepts all defaults.
npm init --init-private -yCreate a private packageWrites the private field as true into the generated package.json.
npm pkg get nameRead 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 --jsonSet a field as JSONParses the value before saving, so true is stored as a boolean rather than a string.
npm pkg delete scripts.buildDelete a package.json fieldRemoves the build entry from scripts; any key is addressed with the same dotted syntax.
npm pkg fixRepair 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.

CommandWhat it does
npm installInstall all project dependenciesWith no arguments it reads package.json and puts every listed dependency into node_modules.
npm install PACKAGEAdd a dependencyInstalls the package with everything it depends on and records it under dependencies.
npm install PACKAGE --save-devAdd a development dependencyRecords the package under devDependencies; -D is the short form.
npm install PACKAGE --save-optionalAdd an optional dependencyRecords it under optionalDependencies; -O is the short form.
npm install PACKAGE --save-peerAdd a peer dependencyRecords it under peerDependencies instead of dependencies.
npm install PACKAGE --save-exactSave an exact versionPins the saved entry to one version number instead of a range; -E is the short form.
npm install PACKAGE --no-saveInstall without savingPuts the package in node_modules but leaves the dependencies list in package.json alone.
npm install -g PACKAGEInstall a package globallyPuts the package in the global prefix folder and links its commands into the prefix's bin directory.
npm install sax@latestInstall 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:reactInstall under an aliasLets two versions of one package sit side by side, or gives a long name a shorter import name.
npm install ./package.tgzInstall 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-packageInstall 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/myprojectInstall from a GitHub repositoryClones the repository with git; npm 12 refuses git dependencies unless the allow-git setting permits them.
npm install --allow-git allAllow 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 --forceForce a fresh downloadFetches remote resources again even when a copy already sits on disk; -f is the short form.
npm install --prefix /path/to/dirInstall in another directoryRuns the command against that folder while the shell stays where it is.
npm ciClean 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 devClean install without devDependenciesKeeps development packages off disk, although they are still resolved and stay in the lockfile.
npm install-testInstall, 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-testClean install, then run testsChains a lockfile install and the test script in one command; cit is the short alias.
npm uninstall PACKAGERemove a dependencyDeletes the package and takes it out of package.json and the lockfile; remove, rm and un are aliases.
npm uninstall lodash --no-saveRemove but keep the entryTakes the files out of node_modules while package.json and the lockfile stay as they were.
npm uninstall -g PACKAGERemove a global packageWorks on the global prefix folder rather than the current project.
npm linkRegister a global linkRun inside the package being developed; it symlinks that folder into the global packages folder.
npm link PACKAGE-NAMELink 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-redisLink a folder in one stepDoes both steps at once: registers that directory globally and links it into the current project.
npm dedupeFlatten duplicated dependenciesMoves shared dependencies further up the tree without installing anything new; ddp is the alias.
npm find-dupesPreview what dedupe would changeRuns the dedupe command as a dry run: it reports the duplicates and leaves the package tree untouched.
npm pruneDelete unlisted packagesClears out of node_modules whatever is not on any package's dependency list.
npm prune --omit=devStrip 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.

CommandWhat it does
npm install-scripts lsList scripts awaiting reviewRead-only: shows each dependency whose install scripts the allowScripts field does not cover yet.
npm approve-scripts canvas sharpApprove named packagesAdds them to allowScripts in package.json, pinned to the version installed now.
npm approve-scripts --allApprove every pending scriptMeant for after a review: allows all packages whose install scripts are still unreviewed.
npm approve-scripts --no-allow-scripts-pin canvasApprove any version of a packageWrites a name-only entry, so later versions of the package keep their approval.
npm approve-scripts --allow-scripts-pendingPreview unapproved scriptsLists the packages that still need a decision and leaves package.json unchanged.
npm deny-scripts telemetry-pkgBlock a package from running scriptsStores an explicit false entry that a later blanket approval does not override.
npm deny-scripts --allDeny every pending scriptMarks all packages with unreviewed install scripts as denied; ones already approved keep their entry.
npm install-scripts prune --dry-runPreview stale approvalsShows which allowScripts entries would go, without removing them.
npm install-scripts pruneDrop stale script approvalsCleans out approvals for packages that are gone or no longer carry an install script.
npm rebuildRebuild installed packagesRuns the install lifecycle scripts again and relinks bins, for example after changing the Node.js version; rb is the alias.
npm patch PKGStart 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-DIRSave edits as a patchWrites the diff to the patches folder, registers it under patchedDependencies and updates the lockfile.
npm patch lsList registered patchesAlso shows how many installed copies each patch applies to.
npm patch rm PKGRemove a patchUnregisters the package's patches and deletes a patch file once nothing else refers to it.

Updating and auditing 16

CommandWhat it does
npm outdatedList outdated dependenciesAsks the registry whether newer versions exist for what the project depends on directly.
npm outdated --allInclude nested dependenciesExtends the report from direct dependencies to every outdated package deeper in the tree.
npm outdated --globalCheck global packagesWith no package.json range to compare against, the wanted column simply repeats the latest version.
npm updateUpdate 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 PACKAGEUpdate one packageLimits the update to the packages named; up and upgrade are aliases.
npm update --saveUpdate and rewrite package.jsonAlso raises the version ranges written in package.json to match what was installed.
npm update -gUpdate global packagesApplies the update to every globally installed package that is out of date.
npm auditScan for known vulnerabilitiesReports the findings without changing anything and exits non-zero when any are found.
npm audit fixInstall compatible security fixesApplies the updates that stay inside the declared dependency ranges.
npm audit fix --forceApply breaking security fixesAlso moves top-level dependencies across major versions, which the plain fix leaves alone.
npm audit fix --dry-run --jsonPreview fixes as JSONShows what the fix would do, with the install details in JSON, and changes nothing.
npm audit fix --package-lock-onlyFix the lockfile onlyUpdates package-lock.json and leaves node_modules as it is.
npm audit --jsonAudit report as JSONPrints the full report in machine-readable form for other tools.
npm audit --audit-level=moderateFail only from a severity levelSets the threshold for a failing exit code; lower severities still appear in the printed report.
npm audit signaturesVerify registry signaturesChecks the signatures and the provenance attestations of the downloaded packages.
npm sbom --sbom-format cyclonedxGenerate 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.

CommandWhat it does
npm run SCRIPTRun 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 runList 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 envList script environment variablesBuilt-in script that prints the variables a script will see, unless the package defines its own env.
npm testRun the test scriptShorthand for the test entry in scripts; t and tst are aliases.
npm startRun the start scriptFalls back to node server.js when scripts has no start entry.
npm stopRun the stop scriptHas no fallback: nothing runs unless the scripts object defines stop.
npm restartRestart 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.jsRun 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.jsRun 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-argumentRun 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 typescriptRun 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 PACKAGESkip 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

CommandWhat it does
npm lsShow the dependency treePrints only the project's immediate dependencies unless a depth or --all is given; list is the alias.
npm ls --allShow the full dependency treeAdds the dependencies of dependencies, down to every level.
npm ls promzardFind where a package is usedNarrows the tree to the paths that lead to the named package.
npm ls --depth DEPTHLimit the tree depthSets how many levels below the direct dependencies are drawn; 0 is the default.
npm ls --globalList global packagesLists what is installed globally rather than in the current project.
npm ls --jsonOutput the tree as JSONPrints JSON data in place of the drawn tree.
npm llList with extended detailsBehaves like ls with the long format switched on; la does the same.
npm explain PACKAGEExplain why a package is installedPrints the dependency chain that pulled the package into the project; why is the alias.
npm query SELECTORQuery dependencies with a selectorTakes a CSS-style selector and returns the matching dependencies as an array of objects.
npm view PACKAGEShow registry data for a packagePrints the metadata of the latest version unless another is named; info and show are aliases.
npm view connect versionsList published versionsPrints the package's whole version history from the registry.
npm view [email protected] dependenciesShow one field of a versionField names after the package limit the output, here to what that release depends on.
npm view npm repository.urlRead 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 TERMSearch the registryMatches the terms against package metadata; find, s and se are aliases.
npm docs PKGNAMEOpen a package's documentationGuesses the documentation URL and opens it in the browser; home is the alias.
npm repo PKGNAMEOpen a package's repositoryOpens the repository page in the browser; without a name it uses the package.json of the current folder.
npm bugs PKGNAMEOpen a package's issue trackerOpens the bug tracker URL or the support mail address; issues is the alias.
npm fundList funding informationDraws a tree of the dependencies that seek funding, each with its funding type and link.
npm rootPrint the node_modules pathWrites the effective folder to standard output, which suits shell scripts.
npm root --globalPrint the global node_modules pathGives the folder where globally installed packages live.
npm prefixPrint the project rootShows the nearest parent directory that holds a package.json or a node_modules folder.
npm prefix -gPrint the global prefix
npm diffCompare 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 masterRun 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 connectOpen a dependency in your editorBrings up the package's folder in the configured editor and rebuilds the package afterwards.

Configuration 13

CommandWhat it does
npm config listShow current settingsLists the settings in effect; add --json for JSON output.
npm config ls -lShow settings with defaultsAdds npm's internal default values to the list.
npm config get KEYRead a settingEchoes the value to stdout; with several keys each value is prefixed by its name.
npm config get registryShow the registry in usePrints the registry URL that installs and the doctor connection check go to.
npm config set KEY=VALUEChange a settingWrites to the user config file unless a location is given; the older KEY VALUE spelling still works.
npm config delete KEYRemove a settingTakes the key out of every configuration file, not just the user one.
npm config editEdit the config fileOpens the user file in your editor; add --global for the global one.
npm config edit --globalEdit the global config fileOpens the global npmrc rather than the per-user one.
npm config fixRepair invalid config entriesUsually this ties loose authentication settings such as _authToken to the registry they belong to.
npm get KEYRead a setting, short formShortcut that behaves exactly like the config get sub-command.
npm set KEY=VALUEChange a setting, short formShortcut for the config set sub-command with the same key=value syntax.
npm COMMAND --KEY=VALUEOverride 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 >> ~/.bashrcEnable tab completionAppends the completion script to the shell start-up file; use ~/.zshrc for zsh.

Publishing and versions 34

CommandWhat it does
npm version patchBump the patch versionRaises the last number in package.json and the lockfile; a prerelease version only loses its suffix.
npm version minorBump the minor versionIn a git repository the bump is also committed and tagged.
npm version majorBump the major version
npm version NEWVERSIONSet an explicit versionTakes any valid semver string in place of a release keyword.
npm version prerelease --preid PRERELEASE-IDBump 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-versionBump without a commit or tagChanges the version in the files only and skips the git commit and tag.
npm version from-gitTake the version from gitReads the most recent git tag and writes it as the package version.
npm packBuild the package tarballWith no argument it packs the current folder into a NAME-VERSION.tgz file in the working directory.
npm pack --dry-runPreview the published filesLists what the tarball would contain without creating it.
npm publishPublish 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=betaPublish under another tagLeaves the latest tag where it is, so a plain install does not pick up this release.
npm publish --access=publicPublish a scoped package publiclyMakes the published package publicly viewable and installable; restricted is the opposite value, meant for scoped packages.
npm publish --dry-runRehearse a publishReports what would be uploaded and makes no change to the registry.
npm publish --provenancePublish with provenanceOn a supported cloud CI/CD service the release is publicly tied to the build that produced it.
npm unpublish PACKAGEUnpublish 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 PACKAGELift a deprecationClears the warnings a deprecate call attached to the package.
npm dist-tag ls PACKAGEList 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 TAGPoint 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 TAGRemove a tagFor tags that are no longer needed; with two-factor writes enabled it asks for a one-time password.
npm access get statusShow a package's access levelActs on the package in the current directory when no name is passed.
npm access set status=publicMake a package publicChanges the access level of a package that is already published to public.
npm access list collaboratorsList a package's collaborators
npm owner ls PACKAGEList package ownersShows the users who may modify the package and push new versions; author is the alias.
npm owner add USER PACKAGEAdd a package ownerThe new maintainer can change metadata, publish versions and add further owners.
npm owner rm USER PACKAGERemove a package ownerTheir rights over the package end immediately.
npm stage publishStage a release for approvalUploads the packed package in a state that stays unavailable to the public until a maintainer approves it.
npm stage listList staged versions
npm stage approve STAGE-IDApprove a staged releasePrompts for two-factor authentication and then publishes the staged package.
npm stage reject STAGE-IDReject a staged releaseAsks for 2FA and permanently removes the staged package.
npm trust github PACKAGE --file FILE --repo OWNER/REPO --allow-publishTrust 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 PACKAGEList trusted publishersShows the existing configuration together with the ID that revoking needs.
npm trust revoke --id ID PACKAGERevoke 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.

CommandWhat it does
npm loginLog in to the registryVerifies the user and stores the credentials in the .npmrc file.
npm login --scope=@mycorp --registry=https://registry.mycorp.comLog in to a private registryAlso maps the scope to that registry for later installs of @mycorp packages.
npm logoutEnd the registry sessionOn token-based registries the token stops working everywhere it is used, not only on this machine.
npm logout --scope=@mycorpLog out of a scoped registryRemoves the scope's link to its registry together with the stored token.
npm whoamiShow the logged-in userPrints the username that belongs to the current token or credentials.
npm profile getShow your registry profileLists every profile property, or only the ones named after it.
npm profile set PROPERTY VALUEChange a profile propertyWorks for email, fullname, homepage and github; the password has its own interactive form.
npm profile enable-2fa auth-and-writesTurn 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-2faTurn off two-factor authentication
npm token listList access tokensTokens appear abbreviated; the full value is never shown.
npm token createCreate an access tokenAsks for your password, and for a one-time password when two-factor authentication is on.
npm token revoke IDRevoke an access tokenAccepts the full token or a shortened id and removes it from the registry at once.
npm org set my-org @mx-smithAdd a user to an orgWithout a role the user joins as a developer.
npm org set my-org @mx-santos adminGive 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-santosRemove an org member
npm org ls my-orgList org membersAdd a username to see just that person's role, or --json for JSON output.
npm team create @org:newteamCreate a teamA team is always written as the org scope and the team name joined by a colon.
npm team add @org:newteam usernameAdd a user to a team
npm team rm @org:newteam usernameRemove a user from a team
npm team ls @orgList an org's teamsGiven a team such as @org:newteam instead, it lists that team's members.

Workspaces 15

CommandWhat it does
npm init -w ./packages/aCreate a workspaceMakes the folder and its package.json and adds it to the workspaces list of the root package.json.
npm install abbrev -w aAdd a dependency to one workspaceSaves the package in workspace a's package.json rather than in the root project.
npm install b -w aDepend on a sibling workspacenpm notices that b is a workspace, links it locally and downloads nothing.
npm run test --workspace=aRun a script in one workspaceSame as changing into packages/a and running the script there.
npm run test --workspace=a --workspace=bRun a script in several workspacesThe flag may be repeated, once for each workspace to target.
npm run test --workspace=packagesRun in a folder's workspacesA parent directory selects all the workspaces inside it.
npm run test --workspacesRun a script in all workspacesGoes through every configured workspace in the order package.json lists them.
npm run test --workspaces --if-presentSkip 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-rootInclude the root project tooAdds the root package to the run alongside the workspaces; --iwr is the shorthand.
npm test -w a -w bRun tests in chosen workspaces-w is the short form of --workspace and can be repeated as well.
npm exec --ws -- eslint ./*.jsRun a command in every workspace--ws is short for --workspaces; here eslint runs once inside each workspace folder.
npm exec --workspace=a -- eslint ./*.jsRun a command in one workspaceThe workspace is given by its name or by the path of its directory.
npm publish --workspacesPublish all workspaces
npm pkg set funding=https://example.com --wsSet a field in every workspaceWrites the same value into the package.json of each configured workspace.
npm fund -w aFunding info for one workspaceFilters the list down to that workspace and what it depends on.

Cache and troubleshooting 14

CommandWhat it does
npm -vShow the npm version
npm install -g npm@latestUpgrade npm itselfOn Linux or macOS it may need sudo, depending on how Node was installed.
npm doctorCheck the npm environmentTests registry access, the Node and git executables, folder permissions and the cache, then lists recommended changes.
npm doctor connectionRun a single doctor checkNames from the synopsis, such as registry, versions, permissions or cache, limit the run to those checks.
npm pingTest the registry connectionContacts the configured registry, checks authentication and prints the response time.
npm cache verifyVerify the cacheChecks the integrity of the cached data offline and garbage-collects what is no longer needed.
npm cache clean --forceClear the cachenpm calls this unnecessary except to reclaim disk space, which is why it insists on the flag.
npm cache lsList cache entriesTakes an optional name@version to narrow the list.
npm cache npx lsList the npx cacheCovers the separate folder where npm exec keeps packages fetched for one-off commands.
npm cache npx rmClear the npx cacheRemoves the keys named after it, or every entry when none is given.
npm help TERMOpen help for a topicShows the documentation page of a known topic and otherwise falls back to a help search.
npm help-search TEXTSearch the npm documentationLists the matching help pages by relevance and opens the page directly when only one matches.
npm COMMAND -hShow a command's usagePrints the usage line and the options that one command accepts.
npm -lShow usage for all commands

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

61 more source pages

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.