Create your first NPX script

Create your first NPX script

NPX script is so useful when you want to execute an NPM package without installing it locally.


2 min read

You might use the npx command many times if you are a JavaScript developer. There are many well-known npx commands on the globe, like npx create-react-app, which will help you create a new ReactJs project.

So what is NPX?

From NodeJs documentation: "npx lets you run code built with Node.js and published through the npm registry."

So in simple words, npx helps you to run npm packages directly from the npm registry. You don't need to install the package in a node_modules folder separately and don't have to run it separately. npx will do all for you.

You'll feel like, you are running a bash script. But under the hood, it's an npm package.

So let's create an NPM package

To start building your npx script, you first need to create a normal NPM library.

You can follow this tutorial to know how to create an NPM Package

Create a name for your library as per your need. Remember the name must have to be globally unique.

We don't need to install libraries in the package, we have it simple for now.

After you have done creating the npm package, you must have 2 files there

  1. package.json <- Contains the metadata of the package
  2. index.js <- Entrypoint for the package

Make required changes in the package.json

  1. Add the Main entry point
"main": "index.js",

It will make the index.js run when the package is called.

  1. Add the bin entry point
"bin": {
    "<package_name>": "index.js"

It will help npx to identify, which file it needs to execute when called.

A complete package.json will look something like this.

Now it's time for index.js

  • Start your index.js file with a #!/usr/bin/env node. It'll help the underlying shell to understand which executable it should use.

  • (Optional but Recommended) After that, use 'use strict' to go into the strict mode

Now you can do whatever you want to do with it. It's now all yours.

You can use it as 1. Portfolio Card, 2. Build small games, 3. Show your blogs here. Use your imagination, and do whatever you like.

An example of index.js

Hooooraaaaay ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

You build your first NPX script.


Before testing, publish the changes you did by using npm publish.

Now to test, use

npx my_awesome_package

It should print

Hello World

Thanks a LOT. ๐Ÿ™Œ

Did you find this article valuable?

Support Arkadip Bhattacharya by becoming a sponsor. Any amount is appreciated!