Language: EN

que-es-y-como-usar-npx-en-npm

What is and how to use NPX

NPX is a Node.js command executor that was introduced in NPM version 5.2.0. Its name is an acronym for “Node Package eXecutor” and its main goal is to facilitate the execution of package commands without having to install them globally.

NPX has been a significant improvement in the Node.js and NPM environment. It allows us to run package commands without the need to install them globally (which simplifies dependency management and improves project portability).

NPX automatically resolves the package location and executes it, without having to install it. What we already know can generate conflicts between projects, or give us problems when sharing projects between teams and/or individuals.

Installing NPX

NPX comes pre-installed with NPM since version 5.2.0, so it does not need to be installed separately.

You can check that it is correctly installed by running this command.

npx -v

Basic usage of NPX

NPX also allows you to run specific package commands without needing to install the package itself.

To do this, we use the syntax npm <package> <command> to run a specific command from a particular package. So,

npx <command> <parameters>

For example, let’s imagine we want to run the command create-react-app, which creates a new React application. The package author provides us with this tool.

Previously, we would have had to install the package globally,

npm install -g create-react-app

But with NPX, we can do the same as follows,

npx create-react-app my-app

In this case, NPX will look for the create-react-app package in the local directories. If it does not find it, it will download it temporarily, execute it, and remove it after use.

This means that no files will be permanently installed on your system, which is a very important advantage over the previous global installation method, which forced you to keep installing more and more things on your machine.

Running commands with specific versions

In addition to running package commands without installing them globally, NPX also allows us to specify the version of a package that we want to use.

To run a command with a specific version of a package, you can use the following syntax:

npx <package>@<version> <command>

For example, if you want to run the command my-command from version 1.0.0 of my-package, you can do it like this:

npx my-package@1.0.0 my-command

NPX will temporarily download version 1.0.0 of my-package, execute the command my-command, and remove it after use.

This can be useful when we need to run commands with specific versions to ensure compatibility or test new features.