走進(jìn)Vue-cli源碼,自己動手搭建前端腳手架工具

前言

前段時(shí)間看了一些vue-cli的源碼缨历,收獲頗深以蕴。本想找個時(shí)間更新一篇文章,但是最近事情比較多辛孵,沒有時(shí)間去整理這些東西丛肮。趁這兩天閑了下來,便整理了一下魄缚,然后跟大家分享一下宝与。如果小伙伴們讀完之后,跟我一樣收獲很多的話鲜滩,還望各位小伙伴們多多點(diǎn)贊收藏支持一下哦伴鳖。

Vue-cli介紹

Vue-cli是一款非常優(yōu)秀的用于迅速構(gòu)建基于Vue的Web應(yīng)用工具。他不同于creat-react-app這樣的工具徙硅,開發(fā)者只需要關(guān)注項(xiàng)目邏輯的代碼榜聂,而不需要關(guān)心webpack打包、啟動Node服務(wù)等等諸如此類的這些問題嗓蘑。Vue-cli是一款基于模板化的開發(fā)工具须肆,等于就是把別人的項(xiàng)目結(jié)構(gòu)給照搬過來匿乃,所有的配置都是暴露出來的,你可以根據(jù)實(shí)際情況去做一些配置的修改豌汇,更加靈活自由一點(diǎn)幢炸。當(dāng)然這對前端工程師提出更高的要求,考慮的東西也變多了拒贱。不過Vue-cli即將發(fā)布3.0的版本宛徊,整個Vue-cli發(fā)生了翻天覆地的變化,它采用跟creat-react-app這類工具的模式逻澳,開發(fā)者只需要關(guān)注項(xiàng)目邏輯的代碼即可闸天。不過目前3.0還沒有出來,所以這次源碼分析我采用的v2.9.3的源碼斜做,也就是2.0的代碼苞氮。后面小伙們在閱讀的時(shí)候要注意以下。

Vue-cli項(xiàng)目結(jié)構(gòu)

image

整個項(xiàng)目的目錄結(jié)構(gòu)如上圖所示瓤逼,下面我大概介紹每個文件夾的東西大致都是干嘛的笼吟。

  • bin (這里放的vue的一些命令文件,比如vue init這樣的命令都是從由這里控制的霸旗。)

  • docs (一些注意事項(xiàng)啥的贷帮,不重要的目錄,可以直接忽略定硝。)

  • lib (這里存放著一些vue-cli需要的一些自定義方法皿桑。)

  • node_modules (這里應(yīng)該就不用我多說了毫目,相信大家都知道了蔬啡,不知道的話可以去面壁去了!●-● )

  • test (單元測試 開發(fā)vue-cli工具時(shí)會用到镀虐,我們讀源碼的時(shí)候可以直接忽略掉箱蟆。)

  • 一些雜七雜八的東西 (比如eslint配置、.gitignore刮便、LICENSE等等諸如此類這些東西空猜,不影響我們閱讀源碼,可以直接忽略掉恨旱。)

  • package.json/README.md (這個不知道也可以去面壁了辈毯!●-●)

綜合來說,我們閱讀源碼所要關(guān)注的只有bin和lib下面即可搜贤,其他的都可忽略谆沃。下面開始閱讀之旅吧

Vue-cli源碼閱讀之旅

在開始讀源碼之前,首先我要介紹一個工具(commander)仪芒,這是用來處理命令行的工具唁影。具體的使用方法可查看github的README.md https://github.com/tj/commander.js 耕陷。小伙伴們再閱讀后面的內(nèi)容之前,建議先去了解一下commander据沈,方便后續(xù)的理解哟沫。這里我們對commander就不做詳細(xì)介紹了。這里vue-cli采用了commander的git風(fēng)格的寫法锌介。vue文件處理vue命令嗜诀,vue-init處理vue init命令以此類推。接著我們一個一個命令看過去孔祸。

vue

引入的包:

  • commander (用于處理命令行裹虫。)

作用: vue這個文件代碼很少,我就直接貼出來了融击。

#!/usr/bin/env node

require('commander')
  .version(require('../package').version)
  .usage('<command> [options]')
  .command('init', 'generate a new project from a template')
  .command('list', 'list available official templates')
  .command('build', 'prototype a new project')
  .parse(process.argv)

這個文件主要是在用戶輸入“vue”時(shí)筑公,終端上顯示參數(shù)的使用說明。具體的寫法可參考 https://github.com/tj/commander.js 上面的說明尊浪。

vue build

引入的包:

  • chalk (用于高亮終端打印出來的信息匣屡。)

作用: vue build命令在vue-cli之中已經(jīng)刪除了,源碼上做了一定的說明拇涤。代碼不多捣作,我就直接貼出來。


const chalk = require('chalk')

console.log(chalk.yellow(
  '\n' +
  '  We are slimming down vue-cli to optimize the initial installation by ' +
  'removing the `vue build` command.\n' +
  '  Check out Poi (https://github.com/egoist/poi) which offers the same functionality!' +
  '\n'
))

vue list

#!/usr/bin/env node
const logger = require('../lib/logger')
const request = require('request')
const chalk = require('chalk')

/**
 * Padding.
 */

console.log()
process.on('exit', () => {
  console.log()
})

/**
 * List repos.
 */

request({
  url: 'https://api.github.com/users/vuejs-templates/repos',
  headers: {
    'User-Agent': 'vue-cli'
  }
}, (err, res, body) => {
  if (err) logger.fatal(err)
  const requestBody = JSON.parse(body)
  if (Array.isArray(requestBody)) {
    console.log('  Available official templates:')
    console.log()
    requestBody.forEach(repo => {
      console.log(
        '  ' + chalk.yellow('★') +
        '  ' + chalk.blue(repo.name) +
        ' - ' + repo.description)
    })
  } else {
    console.error(requestBody.message)
  }
})

引入的包:

  • request (發(fā)送http請求的工具鹅士。)
  • chalk (用于高亮console.log打印出來的信息券躁。)
  • logger (自定義工具-用于日志打印。)

作用: 當(dāng)輸入"vue list"時(shí)(我們測試時(shí)掉盅,可以直接在當(dāng)前源碼文件目錄下的終端上輸入“bin/vue-list”)也拜,vue-cli會請求接口,獲取官方模板的信息趾痘,然后做了一定處理慢哈,在終端上顯示出來模板名稱和對應(yīng)的說明。

效果如下:

  Available official templates:

  ★  browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.
  ★  browserify-simple - A simple Browserify + vueify setup for quick prototyping.
  ★  pwa - PWA template for vue-cli based on the webpack template
  ★  simple - The simplest possible Vue setup in a single HTML file
  ★  webpack - A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.
  ★  webpack-simple - A simple Webpack + vue-loader setup for quick prototyping.

vue init

vue init”是用來構(gòu)建項(xiàng)目的命令永票,也是vue-cli的核心文件卵贱,上面的三個都是非常簡單的命令,算是我們閱讀源碼的開胃菜侣集,真正的大餐在這里键俱。

工作流程

在講代碼之前,首先我們要講一下整個vue-cli初始項(xiàng)目的流程世分,然后我們沿著流程一步一步走下去编振。

image

整個vue init大致流程如我上圖所示,應(yīng)該還是比較好理解的罚攀。這里我大致闡述一下大致的流程党觅。

  1. vue-cli會先判斷你的模板在遠(yuǎn)程github倉庫上還是在你的本地某個文件里面雌澄,若是本地文件夾則會立即跳到第3步,反之則走第2步杯瞻。

  2. 第2步會判斷是否為官方模板镐牺,官方模板則會從官方github倉庫中下載模板到本地的默認(rèn)倉庫下,即根目錄下.vue-templates文件夾下魁莉。

  3. 第3步則讀取模板目錄下meta.js或者meta.json文件睬涧,根據(jù)里面的內(nèi)容會詢問開發(fā)者,根據(jù)開發(fā)者的回答旗唁,確定一些修改畦浓。

  4. 根據(jù)模板內(nèi)容以及開發(fā)者的回答,渲染出項(xiàng)目結(jié)構(gòu)并生成到指定目錄检疫。

源碼內(nèi)容

這里vue-init文件的代碼比較多讶请,我這里就拆分幾塊來看。首先我先把整個文件的結(jié)構(gòu)列出來屎媳,方便后續(xù)的閱讀夺溢。

  /**
   * 引入一大堆包
   */
    const program = require('commander')
    ...
  
   
   /**
    * 配置commander的使用方法
    */     
    
    program
      .usage('<template-name> [project-name]')
      .option('-c, --clone', 'use git clone')
      .option('--offline', 'use cached template')
      
  /**
    * 定義commander的help方法
    */  
    program.on('--help', () => {
      console.log('  Examples:')
      console.log()
      console.log(chalk.gray('    # create a new project with an official template'))
      console.log('    $ vue init webpack my-project')
      console.log()
      console.log(chalk.gray('    # create a new project straight from a github template'))
      console.log('    $ vue init username/repo my-project')
      console.log()
    })
    
    
    function help () {
      program.parse(process.argv)
      if (program.args.length < 1) return program.help() //如果沒有輸入?yún)?shù),終端顯示幫助
    }
    help()
    
    /**
     * 定義一大堆變量
     */
     
     let template = program.args[0]
     ...
     
     /**
      * 判斷是否輸入項(xiàng)目名  是 - 直接執(zhí)行run函數(shù)  否- 詢問開發(fā)者是否在當(dāng)前目錄下生成項(xiàng)目烛谊,開發(fā)者回答“是” 也執(zhí)行run函數(shù) 否則不執(zhí)行run函數(shù)
      */
     
     /**
     * 定義主函數(shù) run
     */
     function run (){
         ...
     }
     
     /**
      * 定義下載模板并生產(chǎn)項(xiàng)目的函數(shù) downloadAndGenerate
      */
      function downloadAndGenerate(){
          ...
      }

整個文件大致的東西入上面所示风响,后面我們將一塊一塊內(nèi)容來看。

引入的一堆包

const download = require('download-git-repo')  //用于下載遠(yuǎn)程倉庫至本地 支持GitHub丹禀、GitLab状勤、Bitbucket
const program = require('commander') //命令行處理工具
const exists = require('fs').existsSync  //node自帶的fs模塊下的existsSync方法,用于檢測路徑是否存在双泪。(會阻塞)
const path = require('path') //node自帶的path模塊持搜,用于拼接路徑
const ora = require('ora') //用于命令行上的加載效果
const home = require('user-home')  //用于獲取用戶的根目錄
const tildify = require('tildify') //將絕對路徑轉(zhuǎn)換成帶波浪符的路徑
const chalk = require('chalk')// 用于高亮終端打印出的信息
const inquirer = require('inquirer') //用于命令行與開發(fā)者交互
const rm = require('rimraf').sync // 相當(dāng)于UNIX的“rm -rf”命令
const logger = require('../lib/logger') //自定義工具-用于日志打印
const generate = require('../lib/generate')  //自定義工具-用于基于模板構(gòu)建項(xiàng)目
const checkVersion = require('../lib/check-version') //自定義工具-用于檢測vue-cli版本的工具
const warnings = require('../lib/warnings') //自定義工具-用于模板的警告
const localPath = require('../lib/local-path') //自定義工具-用于路徑的處理

const isLocalPath = localPath.isLocalPath  //判斷是否是本地路徑
const getTemplatePath = localPath.getTemplatePath  //獲取本地模板的絕對路徑

定義的一堆變量

let template = program.args[0]  //模板名稱
const hasSlash = template.indexOf('/') > -1   //是否有斜杠,后面將會用來判定是否為官方模板   
const rawName = program.args[1]  //項(xiàng)目構(gòu)建目錄名
const inPlace = !rawName || rawName === '.'  // 沒寫或者“.”攒读,表示當(dāng)前目錄下構(gòu)建項(xiàng)目
const name = inPlace ? path.relative('../', process.cwd()) : rawName  //如果在當(dāng)前目錄下構(gòu)建項(xiàng)目,當(dāng)前目錄名為項(xiàng)目構(gòu)建目錄名朵诫,否則是當(dāng)前目錄下的子目錄【rawName】為項(xiàng)目構(gòu)建目錄名
const to = path.resolve(rawName || '.') //項(xiàng)目構(gòu)建目錄的絕對路徑
const clone = program.clone || false  //是否采用clone模式辛友,提供給“download-git-repo”的參數(shù)

const tmp = path.join(home, '.vue-templates', template.replace(/[\/:]/g, '-'))  //遠(yuǎn)程模板下載到本地的路徑

主邏輯

if (inPlace || exists(to)) {
  inquirer.prompt([{
    type: 'confirm',
    message: inPlace
      ? 'Generate project in current directory?'
      : 'Target directory exists. Continue?',
    name: 'ok'
  }]).then(answers => {
    if (answers.ok) {
      run()
    }
  }).catch(logger.fatal)
} else {
  run()
}

對著上面代碼薄扁,vue-cli會判斷inPlace和exists(to),true則詢問開發(fā)者,當(dāng)開發(fā)者回答“yes”的時(shí)候執(zhí)行run函數(shù)废累,否則直接執(zhí)行run函數(shù)邓梅。這里詢問開發(fā)者的問題有如下兩個:

  • Generate project in current directory? //是否在當(dāng)前目錄下構(gòu)建項(xiàng)目

  • Target directory exists. Continue? //構(gòu)建目錄已存在,是否繼續(xù)

這兩個問題依靠變量inPlace來選擇,下面我看一下變量inPlace是怎么得來的邑滨。

const rawName = program.args[1]  //rawName為命令行的第二個參數(shù)(項(xiàng)目構(gòu)建目錄的相對目錄)
const inPlace = !rawName || rawName === '.'  //rawName存在或者為“.”的時(shí)候日缨,視為在當(dāng)前目錄下構(gòu)建

通過上面的描述可知,變量inPlace用于判斷是否在當(dāng)前目錄下構(gòu)建掖看,因此變量inPlace為true時(shí)匣距,則會提示Generate project in current directory? 面哥,反之當(dāng)變量inPlace為false時(shí),此時(shí)exists(to)一定為true毅待,便提示Target directory exists. Continue?尚卫。

Run函數(shù)

邏輯:

image

源碼:

function run () {
  // check if template is local
  if (isLocalPath(template)) {    //是否是本地模板
    const templatePath = getTemplatePath(template)  //獲取絕對路徑
    if (exists(templatePath)) {  //判斷模板所在路徑是否存在
       //渲染模板
      generate(name, templatePath, to, err => {
        if (err) logger.fatal(err)
        console.log()
        logger.success('Generated "%s".', name)
      })
    } else {
       //打印錯誤日志,提示本地模板不存在
      logger.fatal('Local template "%s" not found.', template)
    }
  } else {
    checkVersion(() => {  //檢查版本號
      if (!hasSlash) {  //官方模板還是第三方模板
        // use official templates
        // 從這句話以及download-git-repo的用法尸红,我們得知了vue的官方的模板庫的地址:https://github.com/vuejs-templates
        const officialTemplate = 'vuejs-templates/' + template
        if (template.indexOf('#') !== -1) {  //模板名是否帶"#"
          downloadAndGenerate(officialTemplate) //下載模板
        } else {
          if (template.indexOf('-2.0') !== -1) { //是都帶"-2.0"
             //發(fā)出警告
            warnings.v2SuffixTemplatesDeprecated(template, inPlace ? '' : name)
            return
          }

          // warnings.v2BranchIsNowDefault(template, inPlace ? '' : name)
          downloadAndGenerate(officialTemplate)//下載模板
        }
      } else {
        downloadAndGenerate(template)//下載模板
      }
    })
  }
}

downloadAndGenerate函數(shù)

function downloadAndGenerate (template) {
  const spinner = ora('downloading template')  
  spinner.start()//顯示加載狀態(tài)
  // Remove if local template exists
  if (exists(tmp)) rm(tmp)  //當(dāng)前模板庫是否存在該模板吱涉,存在就刪除
   //下載模板  template-模板名    tmp- 模板路徑   clone-是否采用git clone模板   err-錯誤短信
    
  download(template, tmp, { clone }, err => {
    spinner.stop() //隱藏加載狀態(tài)
    //如果有錯誤,打印錯誤日志
    if (err) logger.fatal('Failed to download repo ' + template + ': ' + err.message.trim())
    //渲染模板
    generate(name, tmp, to, err => {
      if (err) logger.fatal(err)
      console.log()
      logger.success('Generated "%s".', name)
    })
  })
}

lib

generate.js (★)

lib文件下最重要的js文件外里,他是我們構(gòu)建項(xiàng)目中最重要的一環(huán),根據(jù)模板渲染成我們需要的項(xiàng)目。這塊內(nèi)容是需要我們重點(diǎn)關(guān)注的宋舷。

const chalk = require('chalk')
const Metalsmith = require('metalsmith')
const Handlebars = require('handlebars')
const async = require('async')
const render = require('consolidate').handlebars.render
const path = require('path')
const multimatch = require('multimatch')
const getOptions = require('./options')
const ask = require('./ask')
const filter = require('./filter')
const logger = require('./logger')

// register handlebars helper  注冊handlebars的helper
Handlebars.registerHelper('if_eq', function (a, b, opts) {
  return a === b
    ? opts.fn(this)
    : opts.inverse(this)
})

Handlebars.registerHelper('unless_eq', function (a, b, opts) {
  return a === b
    ? opts.inverse(this)
    : opts.fn(this)
})

/**
 * Generate a template given a `src` and `dest`.
 *
 * @param {String} name
 * @param {String} src
 * @param {String} dest
 * @param {Function} done
 */

module.exports = function generate (name, src, dest, done) {
  const opts = getOptions(name, src)  //獲取配置
  const metalsmith = Metalsmith(path.join(src, 'template'))  //初始化Metalsmith對象
  const data = Object.assign(metalsmith.metadata(), {
    destDirName: name,
    inPlace: dest === process.cwd(),
    noEscape: true
  })//添加一些變量至metalsmith中呢袱,并獲取metalsmith中全部變量
  
  //注冊配置對象中的helper
  opts.helpers && Object.keys(opts.helpers).map(key => {
    Handlebars.registerHelper(key, opts.helpers[key])
  })

  const helpers = { chalk, logger }

 //配置對象是否有before函數(shù),是則執(zhí)行
  if (opts.metalsmith && typeof opts.metalsmith.before === 'function') {
    opts.metalsmith.before(metalsmith, opts, helpers)
  }

  metalsmith.use(askQuestions(opts.prompts))  //詢問問題
    .use(filterFiles(opts.filters))  //過濾文件
    .use(renderTemplateFiles(opts.skipInterpolation)) //渲染模板文件


  //配置對象是否有after函數(shù)墩莫,是則執(zhí)行
  if (typeof opts.metalsmith === 'function') {
    opts.metalsmith(metalsmith, opts, helpers)
  } else if (opts.metalsmith && typeof opts.metalsmith.after === 'function') {
    opts.metalsmith.after(metalsmith, opts, helpers)
  }

  metalsmith.clean(false) 
    .source('.') // start from template root instead of `./src` which is Metalsmith's default for `source`
    .destination(dest)
    .build((err, files) => {
      done(err)
      if (typeof opts.complete === 'function') {
      //配置對象有complete函數(shù)則執(zhí)行
        const helpers = { chalk, logger, files }
        opts.complete(data, helpers)
      } else {
      //配置對象有completeMessage撒轮,執(zhí)行l(wèi)ogMessage函數(shù)
        logMessage(opts.completeMessage, data)
      }
    })

  return data
}

/**
 * Create a middleware for asking questions.
 *
 * @param {Object} prompts
 * @return {Function}
 */

function askQuestions (prompts) {
  return (files, metalsmith, done) => {
    ask(prompts, metalsmith.metadata(), done)
  }
}

/**
 * Create a middleware for filtering files.
 *
 * @param {Object} filters
 * @return {Function}
 */

function filterFiles (filters) {
  return (files, metalsmith, done) => {
    filter(files, filters, metalsmith.metadata(), done)
  }
}

/**
 * Template in place plugin.
 *
 * @param {Object} files
 * @param {Metalsmith} metalsmith
 * @param {Function} done
 */

function renderTemplateFiles (skipInterpolation) {
  skipInterpolation = typeof skipInterpolation === 'string'
    ? [skipInterpolation]
    : skipInterpolation    //保證skipInterpolation是一個數(shù)組
  return (files, metalsmith, done) => {
    const keys = Object.keys(files) //獲取files的所有key
    const metalsmithMetadata = metalsmith.metadata() //獲取metalsmith的所有變量
    async.each(keys, (file, next) => { //異步處理所有files
      // skipping files with skipInterpolation option  
      // 跳過符合skipInterpolation的要求的file
      if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
        return next()
      }
      //獲取文件的文本內(nèi)容
      const str = files[file].contents.toString()
      // do not attempt to render files that do not have mustaches
      //跳過不符合handlebars語法的file
      if (!/{{([^{}]+)}}/g.test(str)) {  
        return next()
      }
      //渲染文件
      render(str, metalsmithMetadata, (err, res) => {
        if (err) {
          err.message = `[${file}] ${err.message}`
          return next(err)
        }
        files[file].contents = new Buffer(res)
        next()
      })
    }, done)
  }
}

/**
 * Display template complete message.
 *
 * @param {String} message
 * @param {Object} data
 */

function logMessage (message, data) {
  if (!message) return  //沒有message直接退出函數(shù)
  render(message, data, (err, res) => {
    if (err) {
      console.error('\n   Error when rendering template complete message: ' + err.message.trim())  //渲染錯誤打印錯誤信息
    } else {
      console.log('\n' + res.split(/\r?\n/g).map(line => '   ' + line).join('\n'))
      //渲染成功打印最終渲染的結(jié)果
    }
  })
}

引入的包:

  • chalk (用于高亮終端打印出來的信息。)
  • metalsmith (靜態(tài)網(wǎng)站生成器贼穆。)
  • handlebars (知名的模板引擎题山。)
  • async (非常強(qiáng)大的異步處理工具。)
  • consolidate (支持各種模板引擎的渲染故痊。)
  • path (node自帶path模塊顶瞳,用于路徑的處理。)
  • multimatch ( 可以支持多個條件的匹配愕秫。)
  • options (自定義工具-用于獲取模板配置慨菱。)
  • ask (自定義工具-用于詢問開發(fā)者。)
  • filter (自定義工具-用于文件過濾戴甩。)
  • logger (自定義工具-用于日志打印符喝。)

主邏輯:

獲取模板配置 -->初始化Metalsmith -->添加一些變量至Metalsmith -->handlebars模板注冊helper -->配置對象中是否有before函數(shù),有則執(zhí)行 -->詢問問題 -->過濾文件 -->渲染模板文件 -->配置對象中是否有after函數(shù)甜孤,有則執(zhí)行 -->最后構(gòu)建項(xiàng)目內(nèi)容 -->構(gòu)建完成协饲,成功若配置對象中有complete函數(shù)則執(zhí)行,否則打印配置對象中的completeMessage信息缴川,如果有錯誤茉稠,執(zhí)行回調(diào)函數(shù)done(err)

其他函數(shù):

  • askQuestions: 詢問問題
  • filterFiles: 過濾文件
  • renderTemplateFiles: 渲染模板文件
  • logMessage: 用于構(gòu)建成功時(shí),打印信息

Metalsmith插件格式:

function <function name> {
  return (files,metalsmith,done)=>{
    //邏輯代碼
    ...
  }
}

options.js

const path = require('path')
const metadata = require('read-metadata')
const exists = require('fs').existsSync
const getGitUser = require('./git-user')
const validateName = require('validate-npm-package-name')

/**
 * Read prompts metadata.
 *
 * @param {String} dir
 * @return {Object}
 */

module.exports = function options (name, dir) {
  const opts = getMetadata(dir)

  setDefault(opts, 'name', name)
  setValidateName(opts)

  const author = getGitUser()
  if (author) {
    setDefault(opts, 'author', author)
  }

  return opts
}

/**
 * Gets the metadata from either a meta.json or meta.js file.
 *
 * @param  {String} dir
 * @return {Object}
 */

function getMetadata (dir) {
  const json = path.join(dir, 'meta.json')
  const js = path.join(dir, 'meta.js')
  let opts = {}

  if (exists(json)) {
    opts = metadata.sync(json)
  } else if (exists(js)) {
    const req = require(path.resolve(js))
    if (req !== Object(req)) {
      throw new Error('meta.js needs to expose an object')
    }
    opts = req
  }

  return opts
}

/**
 * Set the default value for a prompt question
 *
 * @param {Object} opts
 * @param {String} key
 * @param {String} val
 */

function setDefault (opts, key, val) {
  if (opts.schema) {
    opts.prompts = opts.schema
    delete opts.schema
  }
  const prompts = opts.prompts || (opts.prompts = {})
  if (!prompts[key] || typeof prompts[key] !== 'object') {
    prompts[key] = {
      'type': 'string',
      'default': val
    }
  } else {
    prompts[key]['default'] = val
  }
}

function setValidateName (opts) {
  const name = opts.prompts.name
  const customValidate = name.validate
  name.validate = name => {
    const its = validateName(name)
    if (!its.validForNewPackages) {
      const errors = (its.errors || []).concat(its.warnings || [])
      return 'Sorry, ' + errors.join(' and ') + '.'
    }
    if (typeof customValidate === 'function') return customValidate(name)
    return true
  }
}

引入的包:

  • path (node自帶path模塊把夸,用于路徑的處理而线。)
  • read-metadata (用于讀取json或者yaml元數(shù)據(jù)文件并返回一個對象。)
  • fs.existsSync (node自帶fs模塊的existsSync方法,用于檢測路徑是否存在膀篮。)
  • git-user (獲取本地的git配置嘹狞。)
  • validate-npm-package-name (用于npm包的名字是否是合法的。)

作用:

  • 主方法: 第一步:先獲取模板的配置文件信息誓竿;第二步:設(shè)置name字段并檢測name是否合法刁绒;第三步:只是author字段。
  • getMetadata: 獲取meta.js或則meta.json中的配置信息
  • setDefault: 用于向配置對象中添加一下默認(rèn)字段
  • setValidateName: 用于檢測配置對象中name字段是否合法

git-user.js

const exec = require('child_process').execSync

module.exports = () => {
  let name
  let email

  try {
    name = exec('git config --get user.name')
    email = exec('git config --get user.email')
  } catch (e) {}

  name = name && JSON.stringify(name.toString().trim()).slice(1, -1)
  email = email && (' <' + email.toString().trim() + '>')
  return (name || '') + (email || '')
}

引入的包:

  • child_process.execSync (node自帶模塊child_process中的execSync方法用于新開一個shell并執(zhí)行相應(yīng)的command烤黍,并返回相應(yīng)的輸出知市。)

作用: 用于獲取本地的git配置的用戶名和郵件,并返回格式 姓名<郵箱> 的字符串速蕊。

eval.js

const chalk = require('chalk')

/**
 * Evaluate an expression in meta.json in the context of
 * prompt answers data.
 */

module.exports = function evaluate (exp, data) {
  /* eslint-disable no-new-func */
  const fn = new Function('data', 'with (data) { return ' + exp + '}')
  try {
    return fn(data)
  } catch (e) {
    console.error(chalk.red('Error when evaluating filter condition: ' + exp))
  }
}

引入的包:

  • chalk (用于高亮終端打印出來的信息嫂丙。)

作用: 在data的作用域執(zhí)行exp表達(dá)式并返回其執(zhí)行得到的值

ask.js

const async = require('async')
const inquirer = require('inquirer')
const evaluate = require('./eval')

// Support types from prompt-for which was used before
const promptMapping = {
  string: 'input',
  boolean: 'confirm'
}

/**
 * Ask questions, return results.
 *
 * @param {Object} prompts
 * @param {Object} data
 * @param {Function} done
 */
 
/**
 * prompts meta.js或者meta.json中的prompts字段
 * data metalsmith.metadata()
 * done 交于下一個metalsmith插件處理
 */
module.exports = function ask (prompts, data, done) {
 //遍歷處理prompts下的每一個字段
  async.eachSeries(Object.keys(prompts), (key, next) => {
    prompt(data, key, prompts[key], next)
  }, done)
}

/**
 * Inquirer prompt wrapper.
 *
 * @param {Object} data
 * @param {String} key
 * @param {Object} prompt
 * @param {Function} done
 */

function prompt (data, key, prompt, done) {
  // skip prompts whose when condition is not met
  if (prompt.when && !evaluate(prompt.when, data)) {
    return done()
  }

  //獲取默認(rèn)值
  let promptDefault = prompt.default
  if (typeof prompt.default === 'function') {
    promptDefault = function () {
      return prompt.default.bind(this)(data)
    }
  }
  //設(shè)置問題,具體使用方法可去https://github.com/SBoudrias/Inquirer.js上面查看
  inquirer.prompt([{
    type: promptMapping[prompt.type] || prompt.type,
    name: key,
    message: prompt.message || prompt.label || key,
    default: promptDefault,
    choices: prompt.choices || [],
    validate: prompt.validate || (() => true)
  }]).then(answers => {
    if (Array.isArray(answers[key])) { 
      //當(dāng)答案是一個數(shù)組時(shí)
      data[key] = {}
      answers[key].forEach(multiChoiceAnswer => {
        data[key][multiChoiceAnswer] = true
      })
    } else if (typeof answers[key] === 'string') {
     //當(dāng)答案是一個字符串時(shí)
      data[key] = answers[key].replace(/"/g, '\\"')
    } else {
     //其他情況
      data[key] = answers[key]
    }
    done()
  }).catch(done)
}

引入的包:

  • async (異步處理工具规哲。)
  • inquirer (命令行與用戶之間的交互跟啤。)
  • eval (返回某作用下表達(dá)式的值。)

作用: 將meta.js或者meta.json中的prompts字段解析成對應(yīng)的問題詢問唉锌。

filter.js

const match = require('minimatch')
const evaluate = require('./eval')
/**
 * files 模板內(nèi)的所有文件
 * filters meta.js或者meta.json的filters字段
 * data metalsmith.metadata()
 * done  交于下一個metalsmith插件處理
 */
module.exports = (files, filters, data, done) => {
  if (!filters) {
    //meta.js或者meta.json沒有filters字段直接跳過交于下一個metalsmith插件處理
    return done()
  }
  //獲取所有文件的名字
  const fileNames = Object.keys(files)
  //遍歷meta.js或者meta.json沒有filters下的所有字段
  Object.keys(filters).forEach(glob => {
    //遍歷所有文件名
    fileNames.forEach(file => {
      //如果有文件名跟filters下的某一個字段匹配上
      if (match(file, glob, { dot: true })) {        
        const condition = filters[glob]
        if (!evaluate(condition, data)) {
          //如果metalsmith.metadata()下condition表達(dá)式不成立隅肥,刪除該文件
          delete files[file]
        }
      }
    })
  })
  done()
}

引入的包:

  • minimatch (字符匹配工具。)
  • eval (返回某作用下表達(dá)式的值袄简。)

作用: 根據(jù)metalsmith.metadata()刪除一些不需要的模板文件腥放,而metalsmith.metadata()主要在ask.js中改變的,也就是說ask.js中獲取到用戶的需求绿语。

logger.js

const chalk = require('chalk')
const format = require('util').format

/**
 * Prefix.
 */

const prefix = '   vue-cli'
const sep = chalk.gray('·')

/**
 * Log a `message` to the console.
 *
 * @param {String} message
 */

exports.log = function (...args) {
  const msg = format.apply(format, args)
  console.log(chalk.white(prefix), sep, msg)
}

/**
 * Log an error `message` to the console and exit.
 *
 * @param {String} message
 */

exports.fatal = function (...args) {
  if (args[0] instanceof Error) args[0] = args[0].message.trim()
  const msg = format.apply(format, args)
  console.error(chalk.red(prefix), sep, msg)
  process.exit(1)
}

/**
 * Log a success `message` to the console and exit.
 *
 * @param {String} message
 */

exports.success = function (...args) {
  const msg = format.apply(format, args)
  console.log(chalk.white(prefix), sep, msg)
}

引入的包:

  • chalk (用于高亮終端打印出來的信息秃症。)
  • format (node自帶的util模塊中的format方法。)

作用: logger.js主要提供三個方法log(常規(guī)日志)吕粹、fatal(錯誤日志)种柑、success(成功日志)。每個方法都挺簡單的匹耕,我就不錯過多的解釋了聚请。

local-path.js

const path = require('path')

module.exports = {
  isLocalPath (templatePath) {
    return /^[./]|(^[a-zA-Z]:)/.test(templatePath)
  },

  getTemplatePath (templatePath) {
    return path.isAbsolute(templatePath)
      ? templatePath
      : path.normalize(path.join(process.cwd(), templatePath))
  }
}

引入的包:

  • path (node自帶的路徑處理工具。)

作用:

  • isLocalPath: UNIX (以“.”或者"/"開頭) WINDOWS(以形如:“C:”的方式開頭)稳其。
  • getTemplatePath: templatePath是否為絕對路徑驶赏,是則返回templatePath 否則轉(zhuǎn)換成絕對路徑并規(guī)范化。

check-version.js

const request = require('request')
const semver = require('semver')
const chalk = require('chalk')
const packageConfig = require('../package.json')

module.exports = done => {
  // Ensure minimum supported node version is used
  if (!semver.satisfies(process.version, packageConfig.engines.node)) {
    return console.log(chalk.red(
      '  You must upgrade node to >=' + packageConfig.engines.node + '.x to use vue-cli'
    ))
  }

  request({
    url: 'https://registry.npmjs.org/vue-cli',
    timeout: 1000
  }, (err, res, body) => {
    if (!err && res.statusCode === 200) {
      const latestVersion = JSON.parse(body)['dist-tags'].latest
      const localVersion = packageConfig.version
      if (semver.lt(localVersion, latestVersion)) {
        console.log(chalk.yellow('  A newer version of vue-cli is available.'))
        console.log()
        console.log('  latest:    ' + chalk.green(latestVersion))
        console.log('  installed: ' + chalk.red(localVersion))
        console.log()
      }
    }
    done()
  })
}

引入的包:

  • request (http請求工具欢际。)
  • semver (版本號處理工具母市。)
  • chalk (用于高亮終端打印出來的信息。)

作用:

  • 第一步:檢查本地的node版本號损趋,是否達(dá)到package.json文件中對node版本的要求,若低于nodepackage.json文件中要求的版本,則直接要求開發(fā)者更新自己的node版本浑槽。反之蒋失,可開始第二步。
  • 第二步: 通過請求https://registry.npmjs.org/vue-cli來獲取vue-cli的最新版本號桐玻,跟package.json中的version字段進(jìn)行比較篙挽,若本地的版本號小于最新的版本號,則提示有最新版本可以更新镊靴。這里需要注意的是铣卡,這里檢查版本號并不影響后續(xù)的流程,即便本地的vue-cli版本不是最新的偏竟,也不影響構(gòu)建煮落,僅僅提示一下。

warnings.js

const chalk = require('chalk')

module.exports = {
  v2SuffixTemplatesDeprecated (template, name) {
    const initCommand = 'vue init ' + template.replace('-2.0', '') + ' ' + name

    console.log(chalk.red('  This template is deprecated, as the original template now uses Vue 2.0 by default.'))
    console.log()
    console.log(chalk.yellow('  Please use this command instead: ') + chalk.green(initCommand))
    console.log()
  },
  v2BranchIsNowDefault (template, name) {
    const vue1InitCommand = 'vue init ' + template + '#1.0' + ' ' + name

    console.log(chalk.green('  This will install Vue 2.x version of the template.'))
    console.log()
    console.log(chalk.yellow('  For Vue 1.x use: ') + chalk.green(vue1InitCommand))
    console.log()
  }
}

引入的包:

  • chalk (用于高亮終端打印出來的信息踊谋。)

作用:

  • v2SuffixTemplatesDeprecated:提示帶“-2.0”的模板已經(jīng)棄用了蝉仇,官方模板默認(rèn)用2.0了。不需要用“-2.0”來區(qū)分vue1.0和vue2.0了殖蚕。
  • v2BranchIsNowDefault: 這個方法在vue-init文件中已經(jīng)被注釋掉轿衔,不再使用了。在vue1.0向vue2.0過渡的時(shí)候用到過睦疫,現(xiàn)在都是默認(rèn)2.0了害驹,自然也就不用了。

總結(jié)

由于代碼比較多蛤育,很多代碼我就沒有一一細(xì)講了裙秋,一些比較簡單或者不是很重要的js文件,我就單單說明了它的作用了缨伊。但是重點(diǎn)的js文件摘刑,我還是加了很多注解在上面。其中我個人認(rèn)為比較重點(diǎn)的文件就是vue-init刻坊、generate.js枷恕、options.jsask.js谭胚、filter.js,這五個文件構(gòu)成了vue-cli構(gòu)建項(xiàng)目的主流程徐块,因此需要我們花更多的時(shí)間在上面。另外灾而,我們在讀源碼的過程中胡控,一定要理清楚整個構(gòu)建流程是什么樣子的,心里得有一個譜旁趟。我自己在讀完整個vue-cli之后昼激,我自己根據(jù)vue-cli的流程也動手搞了一個腳手架工具,僅供大家參考學(xué)習(xí)一下。地址如下:

https://github.com/ruichengping/asuna-cli

最后祝愿大家可以在前端的道路上越走越好橙困!如果喜歡我的文章瞧掺,請記得關(guān)注我哦!后續(xù)會推出更多的優(yōu)質(zhì)的文章哦凡傅,敬請期待辟狈!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市夏跷,隨后出現(xiàn)的幾起案子哼转,更是在濱河造成了極大的恐慌,老刑警劉巖槽华,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件壹蔓,死亡現(xiàn)場離奇詭異,居然都是意外死亡硼莽,警方通過查閱死者的電腦和手機(jī)庶溶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來懂鸵,“玉大人偏螺,你說我怎么就攤上這事〈夜猓” “怎么了套像?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長终息。 經(jīng)常有香客問我夺巩,道長,這世上最難降的妖魔是什么周崭? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任柳譬,我火速辦了婚禮,結(jié)果婚禮上续镇,老公的妹妹穿的比我還像新娘美澳。我一直安慰自己,他們只是感情好摸航,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布制跟。 她就那樣靜靜地躺著,像睡著了一般酱虎。 火紅的嫁衣襯著肌膚如雪雨膨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天读串,我揣著相機(jī)與錄音聊记,去河邊找鬼撒妈。 笑死,一個胖子當(dāng)著我的面吹牛甥雕,可吹牛的內(nèi)容都是我干的踩身。 我是一名探鬼主播胀茵,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼社露,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琼娘?” 一聲冷哼從身側(cè)響起峭弟,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎脱拼,沒想到半個月后瞒瘸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡熄浓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年情臭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赌蔑。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡俯在,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出娃惯,到底是詐尸還是另有隱情跷乐,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布趾浅,位于F島的核電站愕提,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏皿哨。R本人自食惡果不足惜浅侨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望证膨。 院中可真熱鬧如输,春花似錦、人聲如沸椎例。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽订歪。三九已至脖祈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間刷晋,已是汗流浹背盖高。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工慎陵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人喻奥。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓席纽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親撞蚕。 傳聞我的和親對象是個殘疾皇子润梯,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容