Node Package Manager (NPM) allows JavaScript developers to manage and include packages in their projects. Packaged alongside NPM is an extra tool called NPX. NPX enables the execution of Node.js scripts stored in NPM packages or any other web address. Even if the package is not installed, NPX will fetch it into a cache to run the files.
Yet, you've likely encountered numerous libraries or frameworks advising you to employ NPX during the installation of their packages. React even includes a cautionary note, making it clear to developers that the use of NPX is intentional and not a typographical error.
Previously, the process involved installing create-react-app
globally on your machine and then executing create-react-app my-website
. However, since NPM v5.2, there is no longer a necessity to install create-react-app globally (and it's advisable not to). Now, you can effortlessly run npx create-react-app my-website
, and the identical script will be executed to generate your React app.
In this article, you will learn how to create your own NPX tool. The tool we will be creating in this article is pretty simple — it will only multiply 2 or more numbers. You’ll also learn how you can use your tool locally and how you can publish it on the NPM registry for others to use.
Prerequisites
Have Node.js installed on your machine. You can download it here
An NPM account
Project Setup
1. Set Up Your Project
Create a new directory for your NPX tool project and initialize a new Node.js project:
mkdir npx-tool-demo
cd npx-tool-demo
npm init -y
In this step, a few questions about the package such as package name and author name would pop up. Input your answers in the fields provided. A package.json
file would be created in the current directory.
2. Create a Bin Script
In your project, create a bin
directory, and within it, add a script file that will be executed when the tool is run.
Create the directory bin
and inside that directory, update the file index.js
with the following content:
#! /usr/bin/env node
console.log("Hello, World!");
All this file will do (for now) is print “Hello, World!” on your terminal. However, note the code below:
#! /usr/bin/env node
This line should be added to all files that will be executed through the command line. It’s called a Shebang, it is a special line at the beginning of a script or executable file in Unix-like operating systems. It is used to specify the interpreter that should be used to execute the script.
3. Define Your NPX Tool in package.json
Next, update your package.json
file to point to the script you created. Add the following section:
"bin": {
"tool-demo": "bin/index.js"
},
This means that when the user runs npx <package_name>
the script bin/index.js
will run.
4. Test Locally
- To test it locally, you have to install the package globally on your computer:
npm i -g
You should run this command in your tool directory.
- Then, on your terminal, enter the following command to run your NPX tool:
npx tool-demo
Here, tool-demo
is the name of the package. If you have given a different name to your package, make sure to include the package's name.
Using Arguments
In this section, you will implement the functionality of the tool-demo
package. This package should accept at least two arguments (if the arguments are less than two, an error message will appear). Then, it will multiply the two arguments. If the result is NaN,
it means that at least one argument is not a number.
- Replace the content of
bin/index.js
with the following:
#! /usr/bin/env node
const args = process.argv.slice(2);
if (args.length < 2) {
console.error('Please enter at least 2 numbers');
process.exit(1); //an error occurred
}
const total = args.reduce((previous, current) => parseFloat(current) * parseFloat(previous));
if (isNaN(total)) {
console.error('One or more arguments are not numbers');
process.exit(1); //an error occurred
}
console.log(total);
process.exit(0); //no errors occurred
A few things to note:
process.argv
helps get command line inputs. The first two are the script's interpreter (Node) and the package name (tool-demo). Any extra inputs start from index 2. So, to access user inputs, just take elements from index 2 inprocess.argv
.When an error occurs, you can use
process.exit(1)
to indicate that. Ifprocess.exit
receives a value other than 0 it means that an error occurred in the CLI tool.The reduce array function is used to multiply all items in the array one by one.
If the final result of
total
isNaN
, the user will get an error.If the output is successful, the result will be printed out and the process will exit with
0
indicating that the process ended successfully.
Test Locally
Run the command again in your terminal passing two numbers:
npx tool-demo 5 4
To see how the error messages work, input less than two numbers or input strings instead of numbers.
Publish Your NPX Tool
Now that the tool is ready, you can publish it to the NPM registry. This step requires an NPM account, if you don’t have one make sure to create one.
- In your terminal, run the following command to log in using your NPM account:
npm login
You will be prompted to enter your username and password.
- To publish your tool, simply run:
npm publish
This will publish your tool into the NPM registry.
Note: If another tool has the same name as your tool in the NPM registry, you will have to change the name of your package in package.json
and then try publishing again.
Use Your Published Tool
To use your published package, you can run the command below
npx <package_name>
Notice how you don’t need to install the tool globally in this case. You can just run it through NPX.
Others can use your tool with the following command:
npx your-username/tool-demo
Update Your Package
To update your package, you can use the following command:
npm version <type>
Where <type>
determines how to increment the version. It can be one of the following values:
patch
: This action involves increasing the final number in your version, typically indicating a minor modification. For instance, it would update the version from 1.0.0
to1.0.1
.minor
: This will increment the second number in your version and it usually means a minor change that doesn't necessarily affect how the user uses this tool. For instance, it would change the version from1.0.0
to1.1.0
.major
: This involves increasing the initial number in your version, suggesting a substantial change that could impact how the tool is utilized. For instance, it would update the version from1.0.0
to2.0.0
.
After running the above command, run the publish command again to update your tool:
npm publish
Conclusion
In this article, you learned how to create a tool that can be run with NPX. Creating an NPX tool offers a user-friendly and convenient way for others to use your Node.js scripts or tools. It simplifies the execution process and allows users to interact with your tool without worrying about global installations. You also learned how to publish the tool and update it.