Build and publish an npx command to npm with Typescript
Sandro MaglioneGet in touch with me
7 February 2024•
5 min read
npx allows to run a single executable file without installing a full npm package locally.
I recently implemented a static website generator that runs a single
npx command to generate a full html website from markdown:
In this post we learn how to:
- Create an
npxexecutable script using Typescript
- How to configure
package.jsonto publish an
- How to publish the
npxcode to npm
The implementation is up to you 💁🏼♂️
The only requirement is adding a shebang in the first line of the executable code:
shebang: number sign and exclamation mark (
#!) at the beginning of a script.
It tells the operating system (Unix) that this file is a node script.
npx the code in this entry file will be executed (
bin.ts/js in this example 👆).
In the code below the final line executes the full program as a
Promise and logs unexpected errors (using Effect):
package.json we define the
npx command to run using
bin can be either:
- A single string with the name of the file to execute
- An object where the key is the name of the command and the value is the file to execute
In the example below we define a
menimal command that executes the code inside
This will create a
npx menimal command on npm:
There is more.
Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 600+ readers.
In this example I used
tsup.config.ts we define the bundling configuration:
- Specify entry file (
- Specify the output format (
Now we can simply run the
I added also a custom script
copy-templates.tsthat is run using
This will generate a
dist folder containing the bundled code (a single
The final step is publishing the library on npm.
You need to have a valid account on npm to be allowed to publish a package ☝️
We define an
upload command that bundles the code and executes
You will be prompted to login to your npm account. You can also run the
npm logincommand yourself.
This is it!
You can now publish your own
npx commands on npm. This comes handy when you want to execute some code without installing the package locally.
Check out the
menimalpackage on npm.
If you are interested to learn more, every week I publish a new open source project and share notes and lessons learned in my newsletter. You can subscribe here below 👇
Thanks for reading.