The version 7.0.0 of the npm CLI was released in October 2020 and started shipping with Node.js v15.0.0 around the same time. It came with a number of new features which included workspaces, the new peer dependency algorithm, and support for yarn.lock
. In addition to this, npm 7 introduced the new npm exec
command which, like npx
, provided an easy way to run npm scripts "on the fly".
npm exec
?npm exec
is used to run arbitrary commands as if they were npm scripts defined in the package.json
file. It can be used to run commands from npm packages that are not present in the local project dependencies.
For example, the following command
npm exec -- cowsay wow
executes cowsay wow
as if it was a script in the local project's package.json
. The cowsay
command executed by this "inline" or "ad hoc" script comes from the cowsay
package—namely, the cowsay
script is exported by the homonymous package into the node_modules/.bin
directory on npm install
.
If the cowsay
package is not present in the local project dependencies, or if there is no local project with package.json
in it, npm exec
installs the required package and its dependencies to a folder in the npm cache.
npm exec
in an interactive modeWhen npm exec
is run with no command line arguments, it loads a subshell which acts as an interactive npm script environment. This subshell can be used to interactively run and test npm scripts and, for instance, run binaries from the node_modules/.bin
directory.
npm exec
vs npx
In earlier versions of npm, the npm exec
functionality was provided by npx
, a separate binary. With the introduction of npm exec
, npx
had been rewritten to use npm exec
under the hood in a backwards compatible way.
The most noticeable change brought by npm exec
is the addition of the "Need to install the following packages" prompt triggered when the required package(s) are not present in the local project dependencies.