NPX vs NPM
NPM
It does not simply run any package.If you want to run a package using NPM, you must specify that package in your package.json file.
When executables are installed via npm packages, npm links to them:
1 . In local installs, they are linked to from a node_modules/.bin/
directory.
2. In global installs, they are linked to from a global bin/ directory (e.g. /usr/local/bin
).
To locally install,
$ npm install some-package
Now lets say you want NodeJS to execute that package from the command line:$ some-package
The above will fail because only globally installed packages are able to be executed by simply typing their name and hitting the enter key.
To fix this, and have it run, you must type the local path:$ ./node_modules/.bin/some-package
You can technically run a locally installed package by editing your packages.json
file and adding that package in the scripts
section:
{
"name": "whatever",
"version": "1.0.0",
"scripts": {
"some-package": "some-package"
}
}
Then run the script using $ npm run-script
or npm run
NPX:
It will check whether <command>
exists in $PATH
, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package
all you need to do is type:
$ npx some-package
Another major advantage of npx is the ability to execute a package which wasn't previously installed:
$ npx create-react-app my-app
The above example will generate a react
app boilerplate within the path the command had run in, and 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.