Yes, it’s npx, not npm — the difference explained

Yes, it’s npx, not npm — the difference explained

·

0 min read

Recently when I started getting into React I saw a lot of people (including myself) getting confused when seeing npx instead of the very well known npm.

Some of us found it weird but didn’t give much thought, others thought it was a typo and even went into the trouble of “fixing” it by running npm instead of npx.

When I see something happening more than once, I consider it as being worth to be explained. That’s why this article, to all who had the same misunderstanding as me:

It’s not a typo, it’s npx, not npm! :)

NPM

As we might already know, npm is a package manager for Node.js whose goal is automated dependency and package management.

It means that we can specify all our dependencies (packages) for a project in the package.json file and whenever someone has to install the dependencies for it, they should just run npm install and voila!

It also provides versioning i.e. it makes it possible to specify which versions of the dependencies our project depends upon, so we can, for the most part, prevent updates from breaking our project or use our preferred version.

NPX

On the other hand, npx is a tool for executing Node packages and it comes bundled with npm starting with npm5.2 version onward.

What npx does is the following:

  1. By default, it first checks if the package that is to be executed exists in the path (i.e. in our project);
  2. If it does, it executes it;
  3. Else, means that the package has not been installed, so npx installs its latest version and then executes it;

This behavior, that is explained above, is the default one of npx, but it has flags that can be used to prevent it.

For example, if we run npx some-package --no-install means that we're telling npx that it should only try to execute the package named some-package, without installing it if it has not been installed before.

More on npx flags here.

Example

Let's say we have a package named my-package and we want to execute it.

Well, without npx, to execute a package we would have to do it by running it from its local path, like this:

./node_modules/bin/my-package

or define it as a separate script in the scripts section in the package.json file, something like this:

{
  "name": "something",
  "version": "1.0.0",
  "scripts": {
    "my-package": "./node_modules/bin/my-package"
  }
}

and then run it with npm run my-package.

Now, with npx, we can do this easily by just running npx my-package.

Conclusion

So, to reinforce, npm !== npx and I hope this brief article helped in sorting out this misunderstanding.

If you have any questions, feel free to ask away in the comments!

Keep coding, do awesome stuff and stay happy! :)