npx is a Node.js command-line tool which became available with
email@example.com. It enables
npm to eXecute command-line Node.js tools without having them to be installed globally.
Command-line tools like
react-native etc., are commonly installed globally using the
-g flag with
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
npx, all you have to do is install the "global" command-line tool under your
devDependencies, it can then be executed within the context of the project directory using
npx, without them actually being installed globally.
$ npm i -D mocha $ npx mocha
This will install
devDependencies and execute the
mocha command in the context of your present working directory.
mocha on the command line will fail, unless you already installed
npx, you are asking
npm to eXecute the
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
- 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
$ npm firstname.lastname@example.org
npx is a command provided by npm to enable execution of locally installed command-line tools directly from the command line.