Publishing an npx command to npm.
- Published on
- Authors
- Name
- Binh Bui
- @bvbinh
Photo by Venti Views
Introduction
I recently published my first npx command to npm. I wanted to share the process with you. This is a quick guide on how to publish an npx command to npm.
What is npx?
npx is an useful tool to run one-off commands like npx create-react-app my-app
. It is also useful to run commands from npm packages without installing them. For example, npx cowsay moo
will run the cowsay
command from the cowsay
package.
In this article, we will be publishing an npx command to npm. This is a quick guide on how to publish an npx command to npm.
Let start by creating a new directory and initializing a new npm package.
mkdir npx-command
cd npx-command
npm init -y
Next, we will create a new file called index.js
and add the following code.
#!/usr/bin/env node
console.log('Hello World')
The first line of the file is called a shebang. It tells the operating system that this file is a node script. The second line will print Hello World
to the console. We can test this by running the following command.
node index.js
This will print Hello World
to the console. Now, we will add a bin
property to the package.json
file. This will tell npm that this package has a command that can be run from the command line.
{
"name": "npx-command",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin": {
"npx-command": "index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
You can now publish this package to npm by running the following command.
npm publish
After publishing the package, you can run the command by running the following command.
npx npx-command
This will print Hello World
to the console. This can also run the command without installing the package.
You can find the source code for this article on GitHub.
Thanks for reading. If you have any questions, feel free to leave a comment below. You can also follow me on Twitter or GitHub for more content like this.