Today, I’m going to show you how to build your own command line application and deploy it as a NPM package. I will be using npm, Node.js, and Clack to build this.
You can even try it out for yourself right now by running:
Here's a sneak peek of the trivia game (full .gif of play-through + answers at the bottom):
1) Navigate to your command line and run:
npm init -y
This is going to initialize a new project, and the
-y flag automatically answers “yes” to all the prompts. This generates a package.json file that has all the default settings without having to manually provide details.
2) Next, you will run:
npm -install @clack/prompts
Once you do that, you’ll have a framework that lets you create things like spinners, multi-selection, and self-validated cancel logic all with just a few lines of code.
3) Let’s leverage Clack’s built-in setup logic. To create an intro, I’m going to call intro here and pass in this string that let’s the player know they’re about to play in a trivia quiz that tests their CLI knowledge.
4) Since this is a trivia quiz, let’s ask some questions. First, I’ll create a class called Question that requires a question string, an array of potential answers, and the index of the correct answer.
5) Then, I’m going to create 10 question objects using this class template.
6) Now that we’ve got our questions, how do we display them on the command line? We’re going to use Clack’s
select component to do this. All I have to do is pass in the question, initial value, and options, and voila.
7) To make it feel a little more sophisticated, I’m going to add a spinner after the user answers just so they have time to process the UI and makes the program feel intelligent.
8) And then to tie up, I’m going to declare a global variable called totalCorrect which will increment when the player answers a question correctly.
9) At the end, I’ll add some logic to display different outros based on how many questions the player got correct.
And the best part - we’re going to publish this as an npm package so that every developer in the world can download on their machines if they choose to. It’s actually pretty easy.
1) Go to package.json and add “bin”:”./index.js”
4) Then run
3 Min Youtube version (if you prefer that) 👇
Done! But before you start this project for yourself, take into consideration that Clack is really lacking in the documentation. Anything fairly complex, you won’t benefit from the pre-made components of clack/prompts. Here's a list of other CLI frameworks you can use instead.
Check out the full code for the project here:
Just like that, you have made and published your first CLI application! Congrats :)
And, if you'd like to know the answers to all 10 questions in my trivia game, here you go: