Use node to write your own cli tools.

Source: Internet
Author: User

Use node to write your own cli tools.

When receiving a new project, you need to plan the project directory before development, create files one by one, set up the sass compiling environment, and download libraries such as jquery and Swiper... these preparations take a lot of time. Every time you create a project, you will encounter the same problem. Will you repeat it again?
It's time to make a change: write your own cli tool and run a line of command to enter the coding state in 3 seconds!

This article takes my-cli as an example to record the entire process from development to release. After reading this article, you will learn how to develop a cli project from scratch and how to upload it to the github repository, and how to use npm to publish your own package.

Preparation

Before developing a cli tool, you must first think about what it can do. Taking myself as an example, I need a tool that enables me to quickly build a project structure by entering just one line of command, just like this:


Is it cool? Rest assured, very simple.

Start

First, create your cli project and use npm init to create a package. json.

$ mkdir my-cli && cd my-cli$ npm init

Create package. json step by step as prompted. The name attribute is the name you published to npm. This attribute cannot be the same as the name of an existing project on npm. One tips is to use npm install to download the package name you want. If the Error 404 is reported, then your package name is available. The package. json file is created as follows:

{ "name": "my-cli", "version": "0.0.1", "description": "Auto generate project template", "main": "index.js", "bin": {  "my-cli": "./index.js" }, "repository": {  "type": "git",  "url": "git+https://github.com/hlme/my-cli.git" }, "keywords": [  "cli" ], "author": "798400626@qq.com", "license": "MIT", "bugs": {  "url": "https://github.com/hlme/my-cli/issues" }, "homepage": "https://github.com/hlme/my-cli#readme"}

Compile an executable file

Package. json has a "bin" field. After configuration, you can use your command on the console.

"bin": { "my-cli": "./index.js"}

We configured the "my-cli" command to execute the index. js file. Use your favorite editor to create an index. js file in the main directory of the project.


Pay attention to "#! Node is very important. It indicates that node is used to execute this file. Without this statement, the index. js file will be opened in notepad.

Install your package globally

Use npm install-g to install your current project to the global environment. Now you can run the "my-cli" command on the command line.

Quickly generate a project template using the fs Module

The custom commands can be executed. Next, write the code to implement the function. The main function of my-cli is to generate a project template. One idea is to use a templates folder to save the project template, and then use fs. mkdir () to create the project directory, and finally copy the file from the templates folder to the project.

var fs = require('fs');var path = require('path');function copyTemplate (from, to) { from = path.join(__dirname, 'templates', from); write(to, fs.readFileSync(from, 'utf-8'))}function write (path, str, mode) { fs.writeFileSync(path, str)}function mkdir (path, fn) { fs.mkdir(path, function (err) {  fn && fn() })}

Is the core code very simple?

The entire project file structure is similar to this. Put the files you need in the templates folder and copy the files to the project directory using the copyTemplate method.

The code looks ugly when creating a file directory and copying a file

Receive command line parameters

We usually use parameters when using the command line tool, such as webpack-p and express-e. Now we can add the function of receiving command line parameters for our cli. Design four parameters for my-cli to add class libraries to the project.

$ My-cli-j-s-v-B //-j: Add jQuery //-s: Add Swiper //-v: Add Vue //-B: Add Bootstrap

Using the commander package can simplify the Parameter Parsing process. However, this project is relatively simple and I do not want to introduce other packages. It is not difficult to process some simple parameters.

In nodejs, we can use process.argvto obtain the command line. process.argvis an absolute path of node.exe, and the absolute path for executing the js. Use process. argv. slice (2) to obtain the input parameter array.


Check which parameters are input in the command by traversing the parameter array. If you enter a preset parameter, add the corresponding attribute to the config object and determine whether to copy the template file to the project based on onfig during file generation. Continue with the ugly code:


Run locally

Now our project is basically complete. Use npm install-g to install the project to the global environment, create a new project folder, and use the my-cli command to generate the project template.

Released to npm Repository

To publish your package to npm, you must first have an npm account. It is very easy to create an account. Enter npm adduser to complete the creation in three steps.


After creating a user, use npm publish to publish the current project to npm. Then you can use npm install-g my-cli to install your cli tool.

Conclusion

I believe that after reading this article, you will know how to create cli tools based on your needs. In this article, my-cli is relatively simple, and permission is used as an example. To view the complete source code or use this tool, click here: github address.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.