返回

Scaffolding From Scratch Part 2: Creating Your Own CLI Tool

前端

In the previous article, we laid the groundwork for creating our own CLI tool. In this installment, we'll dive into the practical steps of scaffolding your project and setting up its basic structure.

Creating the Scaffolding Folder and Name

Start by creating a new directory for your scaffolding project. The name you choose should be descriptive and relevant to the purpose of your tool. For example, if you're building a scaffolding tool for creating React components, you might name it react-component-scaffold.

Once you've created the directory, navigate into it and initialize a new npm package with the following command:

npm init -y

This will create a package.json file in your directory, which contains basic information about your package, such as its name, version, and description.

Creating the bin and templates Directories

Next, create two new directories within your project directory: bin and templates. The bin directory will hold the executable script for your CLI tool, while the templates directory will contain the template files that your tool will use to generate new projects.

In the bin directory, create a new file named index.js. This file will contain the code for your CLI tool. In the templates directory, create a new directory for each type of project that you want your tool to be able to generate. For example, if you want your tool to be able to generate React component projects, you would create a directory named react-component.

Adding the Basic CLI Tool Code

In the index.js file in the bin directory, add the following code:

#!/usr/bin/env node

const { program } = require('commander');

program
  .command('create')
  .description('Create a new project')
  .argument('<project-name>', 'The name of the new project')
  .action((options) => {
    // Your code to create a new project goes here
  });

program.parse(process.argv);

This code defines a simple CLI tool with a single command called create. When the user runs the create command, it will call the action function, which is where you would put the code to create a new project.

Customizing the CLI Tool

You can customize your CLI tool by adding additional commands, options, and arguments. For example, you could add a command to delete projects or an option to specify the directory where projects should be created.

You can also add your own custom logic to the action function of each command. For example, you could use the fs module to create new files and directories, or you could use the child_process module to run other commands.

Conclusion

In this article, we've covered the basic steps of scaffolding your own CLI tool. In the next article, we'll take a deeper dive into the code and explore some more advanced features of the Commander.js library.