antvaset.com
/
My blog
npm exec: A new way to run commands from npm packages

npm exec: A new way to run commands from npm packages

npm v7 has introduced the new npm exec command which, like npx, can be used to run npm scripts "on the fly".

Published on by Anton Vasetenkov
Topics: npm

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".

What is npm exec?

npm exec

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.

Running npm exec in an interactive mode

When 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.

See also

Loading npm dependencies from multiple registries
How to add npm dependencies from multiple package registries?

Thanks for stopping by my digital playground! If you want to say hi, you can reach out to me on LinkedIn or via email. I'm always keen to chat and connect.

If you really-really like my work, you can support me by buying me a coffee.