Along with npm 5.2 came a new utility, npx, to help with a few popular npm binary execution tasks and give your workflow a boost. In this quick post we’ll go over a few of the most popular use cases.
If you have npm >5.2 installed, npx should already be available. You can run this to make sure:
$ which npx
If for some reason it’s not available, you can install it or update it with this command:
$ npm install -g npx
Shorthand for Calling Local Binaries
Normally, if you want to run a binary that’s installed locally with your project instead of globally on the machine, you’d have to type the following:
In this example we're running the locally-installed jest binary
Well, no more! With npx it’s now as simple as running the following:
$ npx jest
One-Off External Binary Execution
For global binaries that you don’t use very often, you can opt out of having the binary installed on your local machine entirely and instead use npx to download and execute the binary on the fly when needed. This is a popular use case for build tools like Create React App or the webpack CLI. It ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.
Here’s an example using Create React App to start a new React project, where create-react-app doesn’t need to be on the local machine:
$ npx create-react-app best-todo-app-ever
Here’s another example, this time with http-server, to start an http server in the current directory:
$ npx http-server
And, of course, the obligatory cowsay example:
$ npx cowsay Alligator.io!
_______________ < Alligator.io! > --------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||
Testing Out A Different Package Version
You can also specify a specific version of a package to use. For example, let’s run the latest version of uglify-js:
$ npx uglify-js --version
At the time of this writing, the outputted version information is:
Now, we can run the latest version of uglify-js in the 2.x.x series:
$ npx uglify-js@2 --version
And here’s the output:
So with this, you can easily run UglifyJS using the version of your choice:
$ npx firstname.lastname@example.org main.js -o ./dist/main.js
This can be a good way to compare how a newer version of a binary performs before upgrading. You can try with running your locally installed binary first and then run with the latest version using npx and compare the outputs or results.