vue-cli源码版本为3.1.3
命令行工具入口文件在packages/@vue/cli/bin/vue.js
vue-cli的核心命令是create
,整体相对是比较复杂的,我们理解其中的主要逻辑就好。
处理命令行参数
// packages/@vue/cli/bin/vue.js
const chalk = require('chalk')
const semver = require('semver')
const requiredVersion = require('../package.json').engines.node
function checkNodeVersion (wanted, id) {
if (!semver.satisfies(process.version, wanted)) {
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')
进程进来比较进程的node版本和vue-cli所要求的最低node版本,若不符合则提示更新node并退出进程
接着通过commander
生成命令行,通过子命令create
来处理vue create
的命令,最后将项目名称和命令参数传给lib/create
中的函数。
实例化核心方法Creator
async function create (projectName, options) {
if (options.proxy) {
process.env.HTTP_PROXY = options.proxy
}
const cwd = options.cwd || process.cwd()
const inCurrent = projectName === '.'
const name = inCurrent ? path.relative('../', cwd) : projectName
const targetDir = path.resolve(cwd, projectName || '.')
// 验证包名
const result = validateProjectName(name)
if (!result.validForNewPackages) {
console.error(chalk.red(`Invalid project name: "${
name}"`))
result.errors && result.errors.forEach(err => {
console.error(chalk.red(err))
})
exit(1)
}
// 根据参数是否强制移除文件
if (fs.existsSync(targetDir)) {
if (options.force) {
await fs.remove(targetDir)
} else {
await clearConsole()
if (inCurrent) {
const {
ok } = await inquirer.prompt([
{
name: 'ok',
type: 'confirm',
message: `Generate project in current directory?`
}
])
if