不足 60行代码实现一个酷炫的cli工具

849 阅读2分钟

创建文件夹 & 初始化项目

首先创建文件夹,并初始化项目信息 命令就叫 jj-cli

mkdir jj-cli
cd jj-cli
npm init -y

然后新建bin文件夹,在文件夹下新建 jj-cli 文件,首先输入测试代码

#! /usr/bin/env node
console.log('hello jj-cli');

然后在package.json加入 bin配置

 "bin": {
    "jj-cli": "./bin/jj-cli"
  },

在cmd 命令行执行 npm link 执行完成后 就可以验证jj-cli命令了,控制台输出了 hello jj-cli说明第一步配置已经成功了

npm link: 在包文件夹中,将在全局文件夹{prefix}/lib/node_modules/<package>中创建一个符号链接,该 链接链接到 npm link 执行命令的包

bin:项用来指定各个内部命令对应的可执行文件的位置。

WechatIMG252.jpeg

开始cli配置

安装项目所需依赖

npm install commander 
npm install download-git-repo  
npm install shell

commander完整的命令行解决方案

download-git-repo 下载git仓库代码

shelljs 这个库能够让我们在js文件中执行shell命令

chokidar 监听文件变化插件

首先使用commander插件做一个命令行配置在jj-cli 输入代码

#! /usr/bin/env node
const { Command } = require('commander');
const program = new Command();
  program
  .option('-v, --version', ' output the version number')
  .option('-i, --init', ' init project! ')
  .option('-r, --rollup <filename> ', 'create rollup template! ')
  .helpOption('-h, --help', ' can I help you? ')
  .parse(process.argv);
  

然后在cmd命令行输入jj-cli -h就看到了我们平常用的脚手架工具的死丑死丑的帮助信息

WeChate53291922045bef14803d45a813e650a.png

继续完善 输入一下代码,然后输入jj-cli -i 就的到了我们想要命令了

const options = program.opts();
if (options.init){
   console.log(`init project`);
}

WechatIMG253.jpeg

继续完善 引入download-git-repo,shelljs,我预先在github做了一个rollup模版仓库,通过指定的输入命令jj-cli -r执行rollup初始化操作

#! /usr/bin/env node
const { Command } = require('commander');
const download = require('download-git-repo');
const shell = require('shelljs');
const program = new Command();

  program
  .option('-v, --version', ' output the version number')
  .option('-i, --init', ' init project! ')
  .option('-r, --rollup <filename> ', 'create rollup template! ')
  .helpOption('-h, --help', ' can I help you? ')
  .parse(process.argv);

const options = program.opts();

if (options.init){
   console.log(`init project`);
}

if (options.rollup){
   shell.rm('-rf', options.rollup);
   download('direct:https://github.com/***/rollupcli.git', options.rollup, { clone: true }, function (err) {
      if(err){
          console.log('download Error!!')
      }else{
           console.log(' create rollup template! ....');
           console.log('download Success!!')
           console.log('you can');
           console.log(`cd ${options.rollup}`);
           console.log(`yarn install or npm install `);   
      }
   }) 
}

WechatIMG255.jpeg

一个简单的脚手架工具,就做好了

这就完了?

这么丑的cli工具,而且下载的过程中,没有一个loading的效果,都不知道是不是用的电脑太老了,给卡死了, 作为一个有最求的前端你能忍受这样的交互吗?继续往下,加入一些酷炫的插件,来优化我们的脚手架工具的交互效果吧。

npm install @darkobits/lolcatjs 
npm install chalk  
npm install ora@5.3.0 
npm install cfonts 

cfonts 控制台输出性感的字体

截屏2021-10-21 下午1.47.51.png

chalk是一个美化字体颜色背景的插件

WechatIMG251.jpeg

@darkobits/lolcatjs控制台生成渐变字体颜色

46057579-2d15bb00-c10b-11e8-9cb4-d72053db041e.jpeg

ora控制台输出等待loading插件

screenshot-2.gif

插件有了,请开始你的表演

首先引入cfonts

const CFonts = require('cfonts');
if (options.version) {
    CFonts.say('jj-cli', {
	font: '3d',              // define the font face
	align: 'left',              // define text alignment
	colors: ['greenBright','cyanBright'],          // define all colors
	background: 'transparent',  // define the background color, you can also use `backgroundColor` here as key
	letterSpacing: 0,           // define letter spacing
	lineHeight: 0,              // define the line height
	space: true,                // define if the output text should have empty lines on top and on the bottom
	maxLength: '0',             // define how many character can be on one line
	gradient: false,            // define your two gradient colors
	independentGradient: false, // define if you want to recalculate the gradient for each new line
	transitionGradient: false,  // define if this is a transition between colors directly
	env: 'node'                 // define the environment CFonts is being executed in
    });
}

WechatIMG256.jpeg

嗯,有点感觉了,貌似还缺少一个版本信息,表急,让我们继续往下 关于cfonts配置信息可以参考npm根据自己的喜好配置自己心仪的style.、、

介绍下一个插件darkobits/lolcatjs,这个插件..., 直接看效果吧😓

WechatIMG257.jpeg

接下来是loading效果了,在下载代码的时候如果没有loading,还以为是死机了呢,加入了loading相效果起码知道,代码正在下载,网速比较慢而已,ora建议安装5.3.0版本的,现有版本使用的es模块导入方式

WechatIMG260.jpeg

哦,对了还有一个,死丑的帮助命令行信息还没优化呢,好了废话不多说直接上我们最后一个需要介绍的插架chalk,直接看效果吧,是不是比刚开始那个效果好很多了,

WechatIMG259.jpeg

贴代码

#! /usr/bin/env node
const { Command } = require('commander');
const download = require('download-git-repo');
const shell = require('shelljs');
const CFonts = require('cfonts');
const ora = require('ora'); 
const  Printer = require('@darkobits/lolcatjs');
const package=require('../package.json');
const program = new Command();
const chalk = require('chalk');

  program
  .option('-v, --version', chalk.cyan('🎉 output the version number'))
  .option('-i, --init', chalk.cyan('🚄 init project! '))
  .option('-r, --rollup <filename> ', chalk.cyan('📦 create rollup template! '))
  .helpOption('-h, --help', chalk.cyan('🚀 can I help you? '))
  .parse(process.argv);

const options = program.opts();

if (options.version) {
CFonts.say('jj-cli', {
  font: '3d',              // define the font face
  align: 'left',              // define text alignment
  colors: ['greenBright','cyanBright'],         // define all colors
  background: 'transparent',  // define the background color, you can also use `backgroundColor` here as key
  letterSpacing: 0,           // 字间距
  lineHeight:0,              // 行间距
  space: true,                // define if the output text should have empty lines on top and on the bottom
  maxLength: 0,             // define how many character can be on one line
  gradient: true,            // 渐变
  independentGradient: false, // define if you want to recalculate the gradient for each new line
  transitionGradient: false,  // define if this is a transition between colors directly
  env: 'node'                 // define the environment CFonts is being executed in
});  
    const newfontds = Printer.fromString(`       @from xfshz   version ${package.version}`);
    console.log(newfontds);
}


if (options.init){
   console.log(`init project`);
}

if (options.rollup){
   const spinner = ora('⏰ download rollup template ....').start();
   download('direct:https://github.com/xflihaibo/rollupcli.git', options.rollup, { clone: true }, function (err) {
      if(err){
          spinner.fail('download Error!!')
      }else{
           console.log('⏰ create rollup template! ....');
           spinner.succeed('download Success!!')
           console.log(Printer.fromString(`you can`));
           console.log(`cd ${options.rollup}`);
           console.log(`yarn install or npm install `);   
      }
   })
}

最后完整的自定义脚手架工具完成了,老规矩贴出代码,大家可以在此基础上做自定义的其他操作,变成自己的脚手架工具🔧,加油⛽️⛽️⛽️⛽!

这就完了??

发布

npm官网注册账号,然后登录

npm login
# Username: yourname
# Password:
# Email: (this IS public) email@email.com
# Logged in as authorname on https://registry.npmjs.org/.

修改pacckage.jsonversion信息,然后发布

npm publish

通过全局安装就可以使用你的自定义的cli工具了,劲不惊奇,意不意外,一个简易版的自定义cli脚手架工具,就这么简单大减好了,后续小伙伴有什么想法都可以继续在此基础上修改,打造一个自己的cli脚手架工具,加油⛽️⛽️⛽️⛽!