Let's build the simplest CLI tool; create a folder called HelloWorld
and include 2 files:
terminal├── HelloWorld | ├── index.js | ├── package.json
Configure index.js
, adding a shebang at the top to configure the file as a script:
javascript#!/usr/bin/env node console.log('Hello world! 🦄🦄🦄');
Now configure package.json
and set the bin
field with the name of the command that you want to execute:
json{ "name": "helloworld", "version": "0.0.1", "description": "🦄 A simple package that prints a useless hello world", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" }, "bin": { "hello": "index.js" }, "author": "Erik Martín Jordán", "license": "MIT" }
From the HelloWorld
folder, link the package to test it:
javascriptnpm link
From the CLI, run:
terminal> hello Hello world! 🦄🦄🦄
That's it! If you wish, you could publish the package to npm, running npm publish
, but be aware that the package name needs to be available.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.