vue-cli详解

vue-cli_2.x.x

bin/vue

#!/usr/bin/env node
// 主入口
const program = require('commander')

// 对应指令 & 具体文件
program
  .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')
  .command('create', '(for v3 warning only)')

program.parse(process.argv)

bin/vue-build

#!/usr/bin/env node
// 高亮工具
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'
))

bin/vue-create

#!/usr/bin/env node

const chalk = require('chalk')

console.log()
console.log(
  `  ` +
  chalk.yellow(`vue create`) +
  ' is a Vue CLI 3 only command and you are using Vue CLI ' +
  require('../package.json').version + '.'
)
console.log(`  You may want to run the following to upgrade to Vue CLI 3:`)
console.log()
console.log(chalk.cyan(`  npm uninstall -g vue-cli`))
console.log(chalk.cyan(`  npm install -g @vue/cli`))
console.log()

bin/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.
 */
// vue list展示的是所有模版吗?只有官方的吗?会展示本地缓存模版吗? ---只会展示官方文档
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)
  }
})

bin/vue-init

#!/usr/bin/env node
// 加载依赖配置
// 下载远程仓库内容
const download = require('download-git-repo')
// 命令行处理工具
const program = require('commander')
// node下的文件操作了,existsSync - 检测路径是否存在
const exists = require('fs').existsSync
// node自带path模块,拼接路径
const path = require('path')
// 命令行加载效果工具
const ora = require('ora')
// 获取用户的根目录
const home = require('user-home')
// 绝对路径替换成带波浪号的路径
const tildify = require('tildify')
// 高亮
const chalk = require('chalk')
// 用户与脚本的命令行交互工具
const inquirer = require('inquirer')
// rm -rf js版本
const rm = require('rimraf').sync

// 自建工具
const logger = require('../lib/logger')
const generate = require('../lib/generate')
const checkVersion = require('../lib/check-version')
const warnings = require('../lib/warnings')
const localPath = require('../lib/local-path')

// 获取本地路径
const isLocalPath = localPath.isLocalPath
// 获取本地模版路径
const getTemplatePath = localPath.getTemplatePath

/**
 * Usage.
 */
// 面试:如何使用第三方模版?
program
  .usage('<template-name> [project-name]')
  .option('-c, --clone', 'use git clone')
  .option('--offline', 'use cached template')

/**
 * 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()
})

/**
 * Help.
 */

function help () {
  program.parse(process.argv)
  if (program.args.length < 1) return program.help()
}
help()

/**
 * Settings. 主要设置
 */
// 如何取到模版 => 如何获取命令行参数
// 模版名称
let template = program.args[0]
// 是否包含斜杠 => 模版名称是否包含路径层级,官方文档不存在/,如果是引入的第三方文档的话,会存在/
const hasSlash = template.indexOf('/') > -1
// 项目名称
const rawName = program.args[1]
// 输入空的项目名称 => 是否在当前目录新建
const inPlace = !rawName || rawName === '.'
// 当前目录名为项目构建目录名 or 当前目录新建子目录
const name = inPlace ? path.relative('../', process.cwd()) : rawName
const to = path.resolve(rawName || '.')
const clone = program.clone || false

// 拼接目录的地址 => 本地缓存路径
const tmp = path.join(home, '.vue-templates', template.replace(/[\/:]/g, '-'))
if (program.offline) {
  console.log(`> Use cached template at ${chalk.yellow(tildify(tmp))}`)
  template = tmp
}

/**
 * Padding.
 */

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

// 标准的交互询问(确认类型)
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()
}

/**
 * Check, download and generate the project.
 */
// 主功能函数
function run () {
  // check if template is local
  // 是否为本地路径
  if (isLocalPath(template)) {
    // ~/.vue-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(() => {
      // 官方 or 第三方
      if (!hasSlash) {
        // use official templates
        const officialTemplate = 'vuejs-templates/' + template
        // #可用
        if (template.indexOf('#') !== -1) {
          downloadAndGenerate(officialTemplate)
        } else {
          if (template.indexOf('-2.0') !== -1) {
            warnings.v2SuffixTemplatesDeprecated(template, inPlace ? '' : name)
            return
          }

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

/**
 * Download a generate from a template repo.
 *
 * @param {String} template
 */

function downloadAndGenerate (template) {
  const spinner = ora('downloading template')
  spinner.start()
  // Remove if local template exists
  // 删除本地模版
  if (exists(tmp)) rm(tmp)
  download(template, tmp, { clone }, err => {
    spinner.stop()
    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)
    })
  })
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值