Make an NPM Package Executable with npx

Janne Kemppainen |

You may have used the create-react-app package and thought that you’d like to make your own NPM package work in the same way with npx. It’s actually quite easy.

Assuming you have already configured your package with npm init and written the needed code for your package there are only three steps left:

  1. Create a JavaScript file that acts as the entry point for your script and start it with the #!/usr/bin/env node shebang.
  2. Configure the bin field in the package.json file to create a symlink to the script.
  3. Publish the package to NPM or install it on your machine by running npm install -g.

So, your package entry point could be for example in src/index.js:

#!/usr/bin/env node

function main() {
    console.log("Hello from main");
}

if (require.main === module) {
    main();
}

Then you can add this to your package.json:

"bin": {
    "myapp": "src/index.js"
}

The key should match the package name. Alternatively, you can just provide the path to the main file:

"bin": "src/index.js"

This option automatically uses the package name as the executable name. Now you should be able to install the package on your own machine with:

$ npm install -g

And then execute it with npx:

$ npx myapp
Hello from main

If you publish the package to NPM remember to uninstall the local version so that you can verify that the published version works too. Use npm uninstall -g <package-name> to uninstall.

After you’ve published the package it may take a while until npx is able to find it, so you might get the “npm ERR! could not determine executable to run” error. Just wait a few minutes and try again. But the npx myapp command should eventually work (with the correct package name, obviously) without needing to install the package separately.

Subscribe to my newsletter

What’s new with PäksTech? Subscribe to receive occasional emails where I will sum up stuff that has happened at the blog and what may be coming next.

powered by TinyLetter | Privacy Policy