what is NPX and how is it different from NPM?
npm
(Node Package Manager) is most package manager for JavaScript applications. It is the default package manager for Node.js. It consists of:
- an online repository of public and paid-for private projects (packages), called the npm registry.
- a command line client, also called
npm
that to install and manage these packages e.g.npm install some-package
npm
doesn’t run any packages by itself. If we want to run a package using npm, we must define it in package.json
. For example to run some-package
, this is what we’ll need to do:
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"some-package": "some-package"
}
}
Then to run the package:
npm run some-package
As you can see just the simple task of running a package required quite a bit of steps. This is where npx
comes in.
npx
npx
is a tool that is included with npm
. It allows us to run npm packages from the command line, skipping package.json
altogether. It makes it easy to
- run packages that you have installed locally in your project, as well as,
- packages from the online npm registry.
To install npx
if you don’t already have it (check by running which npx
), you can use the following command: npm install -g npx
. Here’s how to use it:
$ npx cowsay npx is best!
______________
< npx is best! >
--------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Differences between npx and npm
Here are the main differences between npx
and npm
:
-
npx
is designed to be used from the command line, whilenpm
is a full-featured package manager that can be used to install, update, and manage npm packages. -
npx
runs a package only once and then exits, whilenpm
usually installs a package and adds it to thedependencies
section of your project’spackage.json
file. -
npx
automatically installs a package (it will prompt you asking for permission) if it is not already present on your system, whilenpm
requires you to explicitly install a package using thenpm install
command. -
npx
is useful for running one-off commands or scripts that are defined in an npm package, whilenpm
is more suitable for managing the dependencies of a long-term project.