NPX and NPM

If you are learning how to use a new Javascript framework or library, you might see the following command npx name-of-package in the Getting Started section. You might say to yourself, wow they made a typo! Actually they did not. npx and npm are very different things, and it was meant to be used that way. Before proceeding, the gist is:

NPM - Manages packages but doesn’t make life easy executing any.

NPX - A tool for executing Node packages.

NPM

We all know what npm does, it is a package manager that manages and installs the application’s modules based on the application’s package.json file. When you run npm install, it scan your package.json file, and installs all neccessary modules based on the versions it specified. npm installs these modules to a folder called ./node_modules</code>. Another common usage is to use npm to install a new module by simply typing npm install cool-thing and npm will install it, add the cool-thing to your application's package.json file.

So what does npx do that is different than npm?

NPX

If npm manages your modules, npx executes them instead. npx checks if the module exists in the path, if it does, it executes it. If it does not, it will installs the module, and executes it.

For example, I want to use the create-react-app module to create a new seed React app. I do not care about saving it to my dependencies in my package.json file, because it’s purpose is to just create the seed app and I will never use it again after. Then npx is the perferred over installing with npm. So if we ran the command:

npx create-react-app my-new-app

If create-react-app has not been installed in the path, npx just installed it for you, and executed the command which resulted in a new React seed app called my-new-app being created. This is a huge advantage that ensures you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.

Conclusion

So in summary, when should I use npx? npx should be used when you want to execute a package or module (that was not previously installed) once and not care to use it again in the future.

Bonus: installing npm packages globally most times requires sudo (administrative user right). With npx you can simply run a node executable anywhere without sudo.