搭建一個 nodejs 腳手架

1 前言

1.1

像咱們熟悉的 vue-cli,taro-cli 等腳手架,只須要輸入簡單的命令 taro init project,便可快速幫咱們生成一個初始項目。在平常開發中,有一個腳手架工具能夠用來提升工做效率。vue

1.2 爲何須要腳手架

  • 減小重複性的工做,從零建立一個項目和文件。
  • 根據交互動態生成項目結構和配置文件等。
  • 多人協做更爲方便,不須要把文件傳來傳去。

1.3 怎樣來搭建呢?

腳手架是怎麼樣進行構建的呢,我是藉助了 taro-cli 的思路。node

1.4 本文的目標讀者

  • 1 想要學習更多和了解更多的人
  • 2 對技術充滿熱情

2 搭建前準備

2.1 第三方工具

  • commander.js,能夠自動的解析命令和參數,用於處理用戶輸入的命令。
  • download-git-repo,下載並提取 git 倉庫,用於下載項目模板。
  • Inquirer.js,通用的命令行用戶界面集合,用於和用戶進行交互。
  • handlebars.js,模板引擎,將用戶提交的信息動態填充到文件中。
  • ora,下載過程久的話,能夠用於顯示下載中的動畫效果。
  • chalk,能夠給終端的字體加上顏色。
  • log-symbols,能夠在終端上顯示出 √ 或 × 等的圖標

2.2 上手

2.2.1 新建一個文件夾,而後npm init初始化

npm 不僅僅用來管理你的應用和網頁的依賴,你還能用它來封裝和分發新的 shell 命令。git

$ mkdir lq-cli
$ npm init 
複製代碼

這時在咱們的 lq-cli 項目中有 package.json 文件,而後須要建立一個 JS 文件包含咱們的腳本就取名 index.js 吧。 package.json 內容以下github

{
  "name": "lq-shell",
  "version": "1.0.0",
  "description": "腳手架搭建",
  "main": "index.js",
  "bin": {
    "lq": "./index.js"
  },
  "scripts": {
    "test": "test"
  },
  "keywords": [
    "cli"
  ],
  "author": "prune",
  "license": "ISC"
}

複製代碼

index.js內容以下mongodb

#!/usr/bin/env node

console.log('Hello, cli!');

複製代碼

到這一步就能夠簡單運行一下這個命令vue-cli

npm link
lq
複製代碼

npm link 命令能夠將一個任意位置的 npm 包連接到全局執行環境,從而在任意位置使用命令行均可以直接運行該 npm 包。 控制檯會輸出Hello, cli!shell

2.2.2 捕獲init之類的命令

前面的一個小節,能夠跑一個命令行了,可是咱們看到的 taro-cli 中還有一些命令,init初始化項目之類。這個時候 commander 就須要利用起來了。 運行下面的這個命令將會把最新版的 commander 加入 package.jsonnpm

npm install --save commander
複製代碼

引入 commander 咱們將 index.js 作以下修改json

#!/usr/bin/env node

console.log('Hello, cli!')

const program = require('commander')
program
  .version(require('./package').version, '-v, --version')    
  .command('init <name>')
  .action((name) => {
      console.log(name)
  })
  
program.parse(process.argv)
複製代碼

能夠經過 lq -v 來查看版本號 經過 lq init name 的操做,action裏面會打印出namebash

2.2.3 對console的美工

咱們看到taro init 命令裏面會有一些顏色標識,就是由於引入了chalk這個包,一樣和 commander 同樣

npm install --save chalk
複製代碼

console.log(chalk.green('init建立'))

這樣會輸出同樣綠色的

2.2.4 模板下載

download-git-repo 支持從 Github下載倉庫,詳細瞭解能夠參考官方文檔。

npm install --save download-git-repo
複製代碼

download() 第一個參數就是倉庫地址,詳細瞭解能夠看官方文檔

2.2.5 命令行的交互

命令行交互功能能夠在用戶執行 init 命令後,向用戶提出問題,接收用戶的輸入並做出相應的處理。用 inquirer.js 來實現。

npm install --save inquirer
複製代碼

index.js文件以下

#!/usr/bin/env node
const chalk = require('chalk')
console.log('Hello, cli!')
console.log(chalk.green('init建立'))
const program = require('commander')
const download = require('download-git-repo')
const inquirer = require('inquirer')
program
  .version(require('./package').version, '-v, --version')    
  .command('init <name>')
  .action((name) => {
      console.log(name)
      inquirer.prompt([
        {
            type: 'input',
            name: 'author',
            message: '請輸入你的名字'
        }
      ]).then((answers) => {
        console.log(answers.author)
        download('',
          name, {clone: true}, (err) => {
          console.log(err ? 'Error' : 'Success')
        })
      })
      
  })
program.parse(process.argv)
複製代碼

2.2.6 ora進度顯示

npm install --save ora
複製代碼

相關命令能夠以下

const ora = require('ora')
// 開始下載
const proce = ora('正在下載模板...')
proce.start()

// 下載失敗調用
proce.fail()

// 下載成功調用
proce.succeed()
複製代碼

2.2.6 log-symbols 在信息前面加上 √ 或 × 等的圖標

npm install --save log-symbols
複製代碼

相關命令能夠以下

const chalk = require('chalk')
const symbols = require('log-symbols')
console.log(symbols.success, chalk.green('SUCCESS'))
console.log(symbols.error, chalk.red('FAIL'))
複製代碼

2.2.7 完整文件以下

#!/usr/bin/env node
const chalk = require('chalk')
console.log('Hello, cli!')
console.log(chalk.green('init建立'))
const fs = require('fs')
const program = require('commander')
const download = require('download-git-repo')
const inquirer = require('inquirer')
const ora = require('ora')
const symbols = require('log-symbols')
program
  .version(require('./package').version, '-v, --version')    
  .command('init <name>')
  .action((name) => {
      console.log(name)
      inquirer.prompt([
        {
            type: 'input',
            name: 'author',
            message: '請輸入你的名字'
        }
      ]).then((answers) => {
        console.log(answers.author)
        const lqProcess = ora('正在建立...')
        lqProcess.start()
        download('github:/Mr-Prune/learn/mongodb-koa',
          name, {clone: true}, (err) => {
          if (err) {
            lqProcess.fail()
            console.log(symbols.error, chalk.red(err))
          } else {
            lqProcess.succeed()
            const fileName = `${name}/package.json`
            const meta = {
              name,
              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(symbols.success, chalk.green('建立成gong'))
          }
        })
      })
      
  })
program.parse(process.argv)
複製代碼

總結

經過上面的例子只是可以搭建出一個簡單的腳手架工具,其實bash還能夠作不少東西,好比 npm 包優雅地處理標準輸入、管理並行任務、監聽文件、管道流、壓縮、ssh、git等,要想了解更多,就要深刻了解,這裏只是打開一扇門,學海無涯。

相關文章
相關標籤/搜索