关于vue-cli4:源码vuecli459一

vue -V产生过程

入口文件

文件门路:/packages/@vue/cli/bin/vue.js

checkNodeVersion

运行vue.js,第一步就是校验Node版本是否合乎package.json中的engines.node的node版本。

const requiredVersion = require('../package.json').engines.node

function checkNodeVersion (wanted, id) {
  if (!semver.satisfies(process.version, wanted, { includePrerelease: true })) {
    console.log(chalk.red(
      'You are using Node ' + process.version + ', but this version of ' + id +
      ' requires Node ' + wanted + '.\nPlease upgrade your Node version.'
    ))
    process.exit(1)
  }
}

checkNodeVersion(requiredVersion, '@vue/cli')

其中npm包semversatisfies办法校验版本是否合乎,若不合乎则退出运行过程。

随后判断Node版本若不是LTS版本,则正告用户降级。

const EOL_NODE_MAJORS = ['8.x', '9.x', '11.x', '13.x']
for (const major of EOL_NODE_MAJORS) {
  if (semver.satisfies(process.version, major)) {
    console.log(chalk.red(
      `You are using Node ${process.version}.\n` +
      `Node.js ${major} has already reached end-of-life and will not be supported in future major releases.\n` +
      `It's strongly recommended to use an active LTS version instead.`
    ))
  }
}

commander 执行命令行输出

commander是一个笨重的nodejs模块,提供了用户命令行输出和参数解析弱小性能。具体能够见上面的参考文章

const program = require('commander')

program
  .version(`@vue/cli ${require('../package').version}`)
  .usage('<command> [options]')

program
  .command('create <app-name>')
  // 省略options
  ...
program
  .command('add <plugin> [pluginOptions]')
  // 省略前面代码,待具体分析
  ...
program.parse(process.argv)

vue -V会触发commander的version函数,输入package.jsonversion属性。

此外,commander还监听执行14个命令,前面会具体分析几个重要的命令

总结

简略介绍了命令行工具vue/@cli执行vue -V的过程,首先会查看运行的node版本是否合乎需要,而后通过commander来解析执行命令行输出。最初再简略介绍了vue/cli还绑定的14个命令行。其中chalkcommander作为cli罕用的开发工具须要熟练掌握,同时也须要理解process的相干api,例如process.version获取node版本等。

参考文章

  • commander.js官网中文文档
  • semver
  • chalk

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理