0304-01如何搭建自己的前端脚手架cli

如何搭建自己的脚手架cli

准备工作:

  • 先准备好模板,方便下载使用

  • 边看边试一下吧

为了整合前端团队代码规范, 以及统一整体架构,可以搭建属于自己小团队的脚手架

本文借鉴vue-cli思路,用到的库有:

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

  • download-git-repo,下载并提取 git 仓库,用于下载项目模板。

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

  • handlebars.js,模板引擎,将用户提交的信息动态填充到文件中。

  • ora,下载过程久的话,可以用于显示下载中的动画效果。

  • chalk,可以给终端的字体加上颜色。

  • log-symbols,可以在终端上显示出 √ 或 × 等的图标。

1、下载依赖

npm init -y
npm i commander download-git-repo inquirer handlebars ora chalk log-symbols -S

2、package.json添加 bin

{
    
    
     "name": "lcq-cli",
     "version": "1.0.0",
     "description": "lcq-cli",
     "bin": {
    
    
      "lcq": "index.js"
     },
     ...
}

3、index.js

const fs = require('fs');
const program = require('commander');
const download = require('download-git-repo');
const handlebars = require('handlebars');
const inquirer = require('inquirer');
const ora = require('ora');
const chalk = require('chalk');
const symbols = require('log-symbols');
 
program.version('1.0.0', '-v, --version')
  .command('init <name>')
  .action((name) => {
    
    
    if(!fs.existsSync(name)){
    
    
      inquirer.prompt([
        {
    
    
          name: 'description',
          message: '请输入项目描述'
        },
        {
    
    
          name: 'author',
          message: '请输入作者名称'
        }
      ]).then((answers) => {
    
    
        const spinner = ora('download...');
        spinner.start();
        download('https://github.com:bear-new/latest-webpack-cli#master', name, {
    
    clone: true}, (err) => {
    
    
          if(err){
    
    
            spinner.fail();
            console.log(chalk.red(err));
          }else{
    
    
            spinner.succeed();
            const fileName = `${
      
      name}/package.json`;
            const meta = {
    
    
              name,
              description: answers.description,
              author: answers.author
            }
            if(fs.existsSync(fileName)){
    
    
              const content = fs.readFileSync(fileName).toString();
              const result = handlebars.compile(content)(meta);
              fs.writeFileSync(fileName, result);
            }
            console.log(chalk.green('success'));
          }
        })
      })
    }else{
    
    
      console.log(symbols.error, chalk.red('项目已存在'));
    }
  })
program.parse(process.argv);

4、执行

node ./index.js init demo

猜你喜欢

转载自blog.csdn.net/jiaojiao51290/article/details/114373316
今日推荐