1. 程式人生 > >vue-cli 3.0腳手架配置及擴充套件 (四):VueConf類

vue-cli 3.0腳手架配置及擴充套件 (四):VueConf類

本類為vue.config.js提供基礎服務,主要業務為根據當前命令獲得有效的頁面資訊,將頁面資訊整合為多頁資料結構,供vue.config.js檔案使用;也同時提供baseUrl屬性,因涉及到多應用會有多個baseURL,baseUrl屬性在npm run serve時恆為dev,在npm run build時,因為構建必須制定一個應用名,所以baseURL為對應的config.app.js中的正確配置

程式碼如下,不懂可留言討論:

/**
 * @fileOverview vue配置所需資料處理類
 * @author Franks.T.D
 * @date 2018/06/17
 */

const path = require('path')
const glob = require('glob')
const AppConf = require('./apps_config_class')
const appconf = new AppConf()
const handleError = Symbol.for('handleError')

module.exports = class VueConf {
  constructor (argv) {
    this.globPathHtml = ['./src/modules/**/index.html', 'template'] // 入口模板正則
    this.globPathJs = ['./src/modules/**/main.js', 'entry'] // 入口指令碼正則
    this.rawArgv = argv.slice(2)
    this.newArgv = argv.slice(3)
    this.baseUrl = 'dev'
    this.pages = Object.create(null)
    this.tempSet = new Set()
    this.init()
  }
  init () {
    try {
      while (this.vueEntryPages(...this.globPathHtml) && this.vueEntryPages(...this.globPathJs)) return this.pages
    } catch (err) {
      console.log('獲取多頁資料錯誤:', err)
    }
  }
  allPages () {
    const result = Object.create(null)
    for (let item of Object.values(appconf.urls)) Object.assign(result, item)
    return result
  }
  validPages () {
    let [result, allPages] = [Object.create(null), this.allPages()]
    if (this.rawArgv[0] === 'serve') {
      if (this.rawArgv.length === 1) {
        result = allPages
      } else {
        for (let item of this.newArgv) Reflect.set(result, item, allPages[item])
      }
    } else if (this.rawArgv[0] === 'build') {
      this.baseUrl = appconf.baseUrl(this.newArgv[0])
      result = appconf.urls[this.newArgv[0]]
    }
    return result
  }
  vueEntryPages (globPath, type) {
    const [pages, tempSet, validPages] = [this.pages, this.tempSet, this.validPages()]
    let [matchList, tempArr, modName] = [glob.sync(globPath), [], null]
    if (matchList.length !== 0) {
      for (let entry of matchList) {
        tempArr = path.dirname(entry, path.extname(entry)).split('/')
        modName = tempArr[tempArr.length - 1]
        if (!Object.keys(validPages).includes(modName)) {
          continue
        } else {
          if (tempSet.has(modName)) {
            Object.assign(pages[modName], { [type]: entry, 'filename': validPages[modName] })
          } else {
            Reflect.set(pages, modName, { [type]: entry }) && tempSet.add(modName)
          }
        }
      }
      if (Object.keys(pages).length !== 0) {
        return true
      } else {
        this[handleError](type)
      }
    } else {
      this[handleError](type)
    }
  }
  [handleError] (type) {
    if (type === 'template') {
      throw new Error('無法獲取多頁入口模板')
    } else if (type === 'entry') {
      throw new Error('無法獲取多頁入口指令碼')
    } else {
      throw new Error('無法獲取多頁資訊')
    }
  }
}
方便理解理解,推薦大家看下《vue-cli 3.0腳手架配置及擴充套件 (二):vue.config.js多頁配置