脚手架工具

84 阅读2分钟

搭建一个空的脚手架

1. 创建一个空目录并初始化npm

mkdir tms-cli & npm init -y

2. 链接到全局调试npm包

  • 在package.json中配置bin目录,并指定要执行的js
{
  "name": "tms-cli",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "bin": {
    "tms-cli": "index.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {}
}

3. 在index.js中添加环境变量

#! /usr/bin/env node

4. 链接到全局的环境,名称是package.json中指定的名称

npm link // 连接到全局
npm unlink // 取消链接

5. 查看链接到全局的包

npm list -g --dept=0

image.png

commander的使用

1. 使用方法

  • 引用资源
const { program } = require("commander");
  • 设置命令
program.option('-别名, --命令名 <type>','描述''默认值');
  • 解析命令
program.parse();
  • 观察解析结果
console.log(program.opts(), program.args);

2. 值类型

  1. Boolean类型
program.option('--first');

在shell中输入node index.js --first,可以观察到一个对象{first:true}; 如果在shell中不输入--first参数,得到的结果对象是{}。

  1. 其他类型
program.option('--first <type>');
  • 该命令要求first必须有参数,如果没有参数则报错,错误提示:error: option '--first ' argument missing;
  • 在shell中输入--first 1,会把first的值设置成1。得到的解析后的对象是:{first:1}。注意该选项会把跟在它后面的部分解析成它的值。即使后面跟的是另外一个参数,如:--frist --xx得到的错误结果{ first: '--second' }。解决的方法就是把--first放在最后,然后再写它的参数,如:--second --first 2
  • 选中的表示该命令必须有值,可以通过.option('--first ','','默认值');在最后添加默认值。
  • 如果选项的值不是必填的,则应当[type]的语法表示该选项的不是必填的。如果在shell中指定--first并没有指定具体的值,则会默认给该选项赋true的Boolean的值。如果在shell中没有指定--first,则解析的结果不会有first。

3. 别名

program.option('-f, --first');
  • 多个别名可以连接在一起写。比如:-f -s,可以简写成-fs。则解析的结果是{fist:true,second:true}
  • 带参数的别名和boolean值的别名,要把带参数的别名写在最后,如:-fsl30,则解析的结果是{fist:true,second:true,last:30}

4. 取反

如果某个选项不需要打开的时候,我们给它设置一个false。当它不是false的时候,它可以用别的string类型的选项,如:c1,c2。这时候就需要取反这个操作。取反操作以no-开头,后接具体的命令,其设置举例如下:

program
  .option("--no-sauce", "Remove sauce")
  .option("--cheese <flavour>", "cheese flavour", "mozzarella")
  .option("--no-cheese", "plain with no cheese");
  • 当no-cheese和chees成对出现的时候,就可以完成不需要的时候设置成false,关闭该选项。
  • 当no-sauce不成对出现,且sauce的值类型是boolean的时候,则表示表示sauce的值默认是true。使用no-sauce可以把它设置成false。

download-git-repo

ora

handlebars

figlet

clear

chalk

open