NPX is a Node.js command executor introduced in NPM version 5.2.0. Its name is an acronym for “Node Package eXecutor” and its main goal is to facilitate running package commands without having to install them globally.
NPX has been a significant improvement in the Node.js and NPM ecosystem. 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. We already know that installing packages globally can cause conflicts between projects, or give us problems when sharing projects between teams and/or people.
Advantages of NPX
Avoids global package installation: With NPX, it is not necessary to install packages globally. Your computer, cleaner and happier 😉.
Avoids dependency conflicts: By not installing packages globally, it avoids dependency conflicts between different projects.
Facilitates package version management: NPX allows running commands with specific versions of packages.
Installing NPX
NPX comes preinstalled with NPM from version 5.2.0, so it is not necessary to install it separately.
You can check that you have it correctly installed by running this command.
npx -v
Basic Usage of NPX
NPX also allows running specific commands from a package 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
For example, imagine we want to run the create-react-app command, which creates a new React application. The package author makes this tool available to us.
Previously, we would have had to install the package globally,
npm install -g create-react-app
But with NPX, we can do the same thing as follows,
npx create-react-app my-application
In this case, NPX will look for the create-react-app package in local directories. If it doesn’t 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 computer.
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 we want to use.
To run a command with a specific version of a package, you can use the following syntax:
npx
For example, if you want to run the command my-command from version 1.0.0 of my-package, you can do it as follows:
npx [email protected] my-command
NPX will temporarily download version 1.0.0 of my-package, execute the my-command 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.
