loyn.es

NPXify your node package.

NPX, that magical command that just makes things work. Here I explore the process for making a package work with NPX.

As I guess most node developers have, I've found myself using npx on the odd occasion. I'd not given much thought to how it actually works, after all it's a quick means to an end in most cases.

I recently had time to play with npx when updating an internal development package for use in a CI workflow. The modification to the package allows it's use as an ad-hoc stand-alone service. It was a  simple process, read on to find out how it's done.

Pre-requisites.

To keep this simple I'll assume the following,

  • you're already setup with a GitHub repository
  • your repo can publish packages somewhere like NPM or GitHub Packages.

The demo repo is set-up in this fashion.

How it went.

To get this working was simple, it required two changes to the repo.

  1. A small update to the repo's package.json file
  2. The creation of a stub script for npx to execute.

Take a look at the following steps, in-situ, in this demo repo.

Update package.json.

This change tells npx what file to execute. Add a bin property to the file with a value that points to your script entry point. In this case it happens to be the file vars.js in the repo's dist directory.

  {
    +  "bin": "./dist/vars.js",
  }

Create vars.ts, the stub script.

This script compiles to the location added to the package.json file. For the demo it's nothing ground-breaking.

  #!/usr/bin/env node
  import { logEnv } from "./index";
  logEnv();

The key to this file is the inclusion of the shebang in the first line. This tells the operating system to run 'env' which will then run 'node'.

Tahdah!

That's it, deploy the package and execute your package with abandon. In this case with the command nxp @monkeyarmada/env_vars