Welcome to an exciting journey into the world of command-line interface (CLI) tools using JavaScript.
In this guide, I'll walk you through creating a CLI tool that sets up a basic project structure, explaining every step and piece of code to ensure you can follow along.
Setting Up Your Development Environment
Before we dive into the world of CLI tools, let's set up our environment:
Install Node.js and npm: Head to Node.js's official website and download the recommended version. Installing Node.js also installs npm, the package manager you'll use to handle JavaScript packages.
Verify Your Installation: Ensure everything is installed correctly by opening your terminal and running:
node --version
npm --version
Seeing version numbers confirms you're all set!
Building Your CLI Tool: Project Setup Automation
Our goal is to create a CLI tool that automatically generates a basic project structure, saving you the hassle of manually creating folders and files every time you start a new project.
Step 1: Kickstarting Your Project
-
Create a Project Directory: This is where your CLI tool's code will reside.
mkdir my-project-setup cd my-project-setup
-
Initialize Your npm Package: This step generates a
package.json
file, which is crucial for managing your project's dependencies and configurations.
npm init -y
Step 2: Crafting Your CLI Application
Create the Main File: Name this file
index.js
. It will contain the logic of your CLI tool.-
Incorporate a Shebang Line: At the beginning of
index.js
, add:
#!/usr/bin/env node
This line tells your system to use Node.js to execute this script.
-
Implementing the Logic: The code below creates a predefined project structure with directories and files:
const fs = require('fs'); // File System module to handle file operations // Define the project structure: directories and their respective files const projectStructure = { 'src': ['index.js'], 'public': ['index.html', 'styles.css'], }; // Iterate over the structure, creating directories and files Object.entries(projectStructure).forEach(([dir, files]) => { fs.mkdirSync(dir, { recursive: true }); // Create directories files.forEach(file => fs.writeFileSync(`${dir}/${file}`, '')); // Create files }); console.log("Project structure created successfully!");
Here's what each part of the code does:
- Require fs module: This is Node.js's file system module, which you'll use to create directories and files.
- Define project structure: We specify which directories to create and what files they should contain.
- Create directories and files: Using
fs.mkdirSync
andfs.writeFileSync
, the script creates each directory and file according to the structure defined.
4. Make Your Script Executable: Modify package.json
to include a "bin"
section. This tells npm which command should execute your script:
"bin": {
"setup-project": "./index.js"
}
Step 3: Testing and Linking Your Tool Locally
Before sharing your tool, test it:
Link Your Tool: Run
npm link
in your project directory. This command creates a symlink that allows you to run your CLI tool from anywhere in your terminal.Run Your Tool: Simply type
setup-project
in your terminal in project's directory. If everything is set up correctly, you'll see the "Project structure created successfully!" message, with the project structure as mentioned.
YES, THAT'S ALL IT TOOK!
Step 4: Enhancing Functionality
Your tool now automates project setup, but there's room for improvement. Consider adding more features or handling user input to customize the project structure. Explore packages like yargs
for parsing command-line arguments. You can learn more about yargs through their official documentation here.
Step 5: Sharing Your Tool on npm
Ready to share your CLI tool with the world? Here's how:
Sign Up on npm: If you don't have an account, create one at https://www.npmjs.com/signup.
Log In via Terminal: Run
npm login
and enter your npm credentials.Publish Your Package: In your project directory, execute
npm publish
.
Congratulations! Your CLI tool is now available on npm for everyone to use.
If you have followed me till here, do checkout my first CLI tool I made in Javascript, and published on npm: Naturalshell. Naturalshell provides AI in your terminal, no need of memorising shell commands now!
You can checkout the npm package here and the github repository here.
Do drop a ⭐, and feel free to add new features and build on naturalshell with me!This tool leverages AI to parse natural language and provide shell commands to users based on their needs. Beyond just providing commands, it also offers concise explanations, ensuring users not only know what to do but understand how it works. With the added convenience of editing commands directly within the tool and the ability to execute them immediately, NaturalShell delivers a user-friendly, intuitive experience
Wrapping Up
You've taken a significant first step into the world of CLI tool development with JavaScript. By building a simple yet functional tool, you've learned the essentials of creating, testing, and publishing CLI applications. Keep experimenting, learning, and building. The command line is a powerful ally, and now, it's yours to command. Happy coding!
If you found this guide helpful and created your own awesome CLI tool, I'd love to see it! Please share your GitHub repositories in the comments section below. Let's build together!
Top comments (22)
I wonder where do you learn this knowledge to write this index.js file? I want to create a CLI for my project for the initial template of the project quickly, but I can`t find a tutorial or document for CLI development
@ztf4080 I've created a CLI tool for this exact purpose - 'Genzo'. Genzo can rapidly scaffold projects using your custom templates from local and remote sources. It automates the most common tasks involved in setting up a JavaScript-based project.
Do check it out and let me know your thoughts!
github.com/FatehAK/genzo-cli
Looks like a good project, I will learn it😎
I've found that a mix of official documentation, such as Node.js and npm guides, combined with community resources like GitHub projects and Stack Overflow discussions, is incredibly helpful. For CLI development specifically, exploring similar npm packages, or exploring different implementations for the same functionalities really helps.
For creating a CLI to provide the initial template of the project, you can either buiild on this, or for a more sophisticated and complex approach with more features you can explore different npm packages and their respective github repos, like this.
Your advice is very comprehensive and I should find my way to this now. Super Thanks!
Glad I could help!
There is no ready-made tutorial for implementing CLI, but you can learn about its implementation principle through some articles, such as: segmentfault.com/a/1190000039267390
原来思否有这么好的教程啊,感谢老哥!
Although I am not a beginner, this is a one-stop guide for creating CLI tools. It is an excellent self-learning experience for nodejs and cli.
I would love another tutorial explaining other concepts, such as spawn processes, event-emitters, streams etc.
Thank you for your words @shikhar13012001 😇.
Right now I am learning about language parsing and AST creation, but tutorial on these concepts is definitely on my radar now.
Cooking more content now - stay connected 🚀
Your guide to building CLI tools in JavaScript is incredibly comprehensive and well-explained! I appreciate how you break down each step, making it easy for beginners to follow along and understand the process. There is one such website named ProgrammingHomeworkHelp.com has been an invaluable resource for me as a budding JavaScript developer. It's inspired me to explore further, and experiment with new ideas.
Thank you for your kind words Enzo! 🙌
One can also use oclif, for building CLI tools in JS, even few large companies use it to build there CLI u can see those organizations at bottom of oclif webpage
Yeah! oclif provides a great framework for building CLI tools. Though imo can be overwhelming to start with.
This guide is helpful, thanks @shreshthgoyal
🙌🙌
Wow! Really great article for building CLI tool. I was EXACTLY looking for such article.
Glad it could be of help 😄😄
A good one indeed
Thanks, Raj😎
So informative. A good guide to start tinkering with Javascript and CLI.
Thank you John! 😇