What is npx?
What is npx
?#
npx
is a Node.js command-line tool which became available with npm@5.2.0
. It enables npm
to eXecute command-line Node.js tools without having them to be installed globally.
Command-line tools like mocha
, gulp
, react-native
etc., are commonly installed globally using the -g
flag with npm
.
However, a globally installed package has two major problems:
- Different projects may depend on different versions of the same package
- Users may be reluctant to install a global utility just for your project
When using npx
, all you have to do is install the "global" command-line tool under your dependencies
or devDependencies
, it can then be executed within the context of the project directory using npx
, without them actually being installed globally.
For example:
$ npm i -D mocha
$ npx mocha
This will install mocha
under devDependencies
and execute the mocha
command in the context of your present working directory.
Simply executing mocha
on the command line will fail, unless you already installed mocha
. With npx
, you are asking npm
to eXecute the mocha
command.
Another popular way of executing command-line tools without installing them globally is to use npm scripts. Within the script definition, you can call command-line tools like they were installed globally.
So why use npx
over npm scripts? Two good reasons:
- You don't need to edit the
package.json
file - You can direcly execute the tool from the command line
Use and discard commands#
There is another aspect to npx
; when you execute it in a directory where it was not installed as dependency. In such a case, npx <package>
will install the package and execute the command. The next time you run npx <package>
, the latest version will be installed and executed. Meaning, the installation is not "saved".
This feature is great for trying out command-line tools without installing them permanently. It is also excellent for using generators like react-native
which you use once in a while and will need to use the latest version when you do.
If you need to execute a particular version of a tool, you can specify the semantic version using the format npx <package><@n.n.n>
.
Eg:
$ npm react-native@0.55.0
Summary#
npx
is a command provided by npm to enable execution of locally installed command-line tools directly from the command line.