使用typescript重构cli

typescript中project-cli项目文档

项目需求:

  • 从后端开发规范和项目开发规范中梳理出后端项目共同的配置文件,使用typescript重构project-cli

需要用到的相关模块

commander.js:可以自动的解析命令和参数,用于处理用户输入的命令。

download-git-repo:下载并提取 git 仓库中的配置文件,用于下载项目模板。

Inquirer.js:通用的命令行用户界面集合,用于和用户进行交互。

ora:下载过程久的话,可以用于显示下载中的动画效果。(暂时未用到)

typescript:typescript模块

@types/node: 在typescript中使用node

@type/commander:typescript可以自动的解析命令和参数,用于处理用户输入的命令。

@types/inquirer:typescript中实现用户交互

项目实现流程

1.下载安装nvm(node版本管理工具)

2.下载nodejs版本(建议下载v10.15.3)

3.新建文件夹,切换到文件夹中并初始化文件夹(npm init -y),生成package.json文件

4.安装上面提到过的这几个脚手架依赖工具,执行npm install typescript chalk commander download-git-repo inquirer ora @types/node @type/commander @types/inquirer --save npm install tslint --save-dev完成安装

5.使用tsc —init初始化project-cli项目,生产tsconfig.json文件,将outDir": "./" 取消注释并修改为"outDir": "./bld"(outDir:配置typescript中编译文件存储路径)

6.构建项目目录

使用typescript重构cli_第1张图片

7.在package.json中新增bin配置(配置命令入口文件)

"bin": {

    "tcli": "./bld/bin/main.js"

  }, 

8.构建main.ts(程序入口文件)

#! /usr/bin/env node

process.env.NODE_PATH = __dirname + "/../node_modules";
import command = require("commander");
import * as path from "path";

const res = (command: string) => path.resolve(__dirname, "../commands/", command);

command
    .version("1.0.0");

command
    .usage("");

command
    .command("init")
    .description("Generate a new my project")
    .alias("i")
    .action( () => {
        require(res("init"));
    });

command.parse(process.argv);

if (!command.args || !command.args.length) {
    command.help();
}

9.构建init.ts(程序主逻辑文件)

import * as chalk from "chalk";
import command = require("commander");
import download = require("download-git-repo");
import * as fs from "fs";
import * as inquirer from "inquirer";
import ora = require("ora");
import * as path from "path";

import { branchNodeConf, branchPythonConf, branchTypescriptConf, url, Answers } from "../config/setting";

const spinner = ora("Downloading please wait......");
const option: string = command.parse(process.argv).args[0];
const defaultName: string = typeof option === "string" ? option : "My-project";
const questionList: any[] = [
    {
        type: "input",
        name: "Project name",
        message: "Project name",
        default: defaultName,
        filter(val: string): string {
          return val.trim();
        },
        validate(val: string): any {
          const validate = (val.trim().split(" ")).length === 1;
          return validate || "Project name is not allowed to have spaces ";
        },
        transformer(val: string): string {
          return chalk.default(val);
        }
    },
    {
        type: "input",
        name: "description",
        message: "Project description",
        default: "My project",
        validate(val: string): boolean {
          return true;
        },
        transformer(val: string): string {
          return chalk.default(val);
        }
      },
    {
        type: "input",
        name: "author",
        message: "Author",
        default: "project author",
        validate(val: string): boolean {
          return true;
        },
        transformer(val: string): string {
          return chalk.default(val);
        }
      },
    {
        type: "list",
        name: "language type",
        message: "language type",
        choices: [
            "Nodejs",
            "Typescript",
            "Python"
        ],
        default: "nodejs",
        filter: function(val: string): string {
            return val.toLowerCase();
        }
    }
];

// ts的泛型(重点了解)
inquirer.prompt(questionList).then(answers => {
    const answer = answers["Project name"];
    const type = answers["language type"];
    if (type === "nodejs") {
        spinner.start();
        download(url + branchNodeConf, answer,  { clone: true }, (err) => {
          if (err) {
              spinner.stop();
              console.log(err);
          } else {
              spinner.stop();
              console.log(chalk.default("项目初始化成功"));
          }
      });
      } else if (type === "typescript") {
        spinner.start();
        download(url + branchTypescriptConf, answer, { clone: true }, (err) => {
          if (err) {
              spinner.stop();
              console.log(err);
          } else {
              spinner.stop();
              console.log(chalk.default("项目初始化成功"));
          }
      });
      } else {
        spinner.start();
        download(url + branchPythonConf, answer, { clone: true }, (err) => {
          if (err) {
              spinner.stop();
              console.log(err);
          } else {
              spinner.stop();
              console.log(chalk.default("项目初始化成功"));
          }
      });
      }
  });

10.使用vscode编译typescript文件

11. 在终端安装我们构建的包npm install -g

12.测试使用命令tcli init项目构建是否成功

项目代码

你可能感兴趣的:(typescript)