Difference between npm and npx
In recent days, almost every project depends on some other libraries/packages to speed up their development and to use the functionality of those libraries/packages. To get these packages, we use
npm packages must be locally installed and correctly versionend. But most of the time, developers get confused which command to use when dealing with these.
What are npm & npx commands and what are they used for?
When we install packages via
npm, those packages can be installed globally, but this is not the default behaviour. It means all the packages will be downloaded in a subdirectory (named “
node_modules”) of the current working directory (means packages will be installed locally within that directory).
How to install a package using npm?
If we need to install a package globally then we need to provide argument
-g with the command, like:
$ npm install -g package_name
Now, when executables are installed via
npm create links to those on below paths:
- locally installed packages will have executable links created at
- globally installed packages will have links created from the global
bin/directory (for example:
/usr/local/binon Linux or at
%AppData%/npmon Windows). For locally installed packages, if we need to execute a package with
npm, either we have to type the local path like this:
Or we need to specify this package in the script section of our project’s
package.json file like this:
And then we can run the script using
$ npm run package-name
How and when to use npx?
npx is an
npm package used to execute any package on the
npm registry directly without installing it.
npx helps us avoid versioning, dependency issues and installing unnecessary packages that we just want to try out.
If we need to execute a package then we need to take some additional steps and that’s where
npx comes into picture.
npx comes bundled with
npm version 5.2+
If we want to execute a locally installed package, all we need to do is type:
$ npx package-name
npx will check whether package-name exists in
$PATH, or in the local project binaries, and if so it will execute it. Most of the time, we need to run the
npx package-name command only once related to one package in a project. It also allows developers to execute any Package without even downloading that in
node_modules. For example, if we run below command then it will display the result without downloading that package in our
$ npx cowsay wow
npm is a tool that is used to install packages and
npx is a tool that is used to execute packages.
Hope this blog helps you understand
npx better. Please feel free to contact us in case of any queries and our team of experts will be happy to help.
Engineering Manager @ BigStep Technologies. Specializes in FullStack Development.