说起源码,给我的第一印象是苦涩无趣,所以也一直是心里想着要读,但是一直未下手,刚好最近手上活儿少了点,又刚好在若川源码共读群里,就开始了
若川大佬的源码攻读已经有好多期了,我为什么从这篇vue3.2如何发布开始呢,大概是被这个标题吸引了吧,确实想知道平尤大到底怎么整的吧
当然我所写的是我觉得学到的必要的,详细的至[https://juejin.cn/post/6997943192851054606]查看更详细的调试及解读
vue3.2如何发布具体化今天要解读的是scripts/release.js文件
1. 环境及文件头部的依赖声明
1.1 环境
克隆项目,装包,修改指令
// 克隆项目
git clone https://github.com/lxchuan12/vue-next-analysis.git
git clone https://github.com/vuejs/vue-next.git
// 装包
cd vue-next
yarn install
// 修改指令
"scripts": {
// --dry 参数是我加的,如果你是调试 代码也建议加
// 不执行测试和编译 、不执行 推送git等操作
// 也就是说空跑,只是打印,后文再详细讲述
"release": "node scripts/release.js --dry",
"preinstall": "node ./scripts/checkYarn.js",
}
2. 头部依赖及声明
2.1 依赖
// vue-next/scripts/release.js
const args = require('minimist')(process.argv.slice(2))
// 文件模块
const fs = require('fs')
// 路径
const path = require('path')
// 控制台
const chalk = require('chalk')
const semver = require('semver')
const currentVersion = require('../package.json').version
const { prompt } = require('enquirer')
// 执行子进程命令 简单说 就是在终端命令行执行 命令
const execa = require('execa')
可以在 node_modules 找到对应安装的依赖,找到其README了解其大概用法解释和对应的github地址
2.1.1 minimist
var argv = require('minimist')(process.argv.slice(2));
console.log(argv);
其中的第一和第二个元素是Node可执行文件和被执行JavaScript文件的完全限定的文件系统路径,无论你是否这样输入他们。
执行
node test.js
process.argv前两个参数如下
{
_: [
'/Users/jryg/.nvm/versions/node/v14.18.2/bin/node',
'/Users/jryg/Desktop/源码read/vue-next-analysis/vue-next/scripts/test.js'
]
}
minimist 作用就是解析之后的参数,如下:
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
2.1.2 chalk 终端多色彩输出
在终端多色彩输出
2.1.3 semver 语义化版本
2.1.4 enquirer 交互式询问 CLI
2.1.5 execa 执行命令
const execa = require('execa');
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
})();
2.2 声明
2.2.1
// vue-next/scripts/release.js
// 对应 yarn run release --preid=beta
// beta
const preId =
args.preid ||
(semver.prerelease(currentVersion) && semver.prerelease(currentVersion)[0])
// 对应 yarn run release --dry
// true
const isDryRun = args.dry
// 对应 yarn run release --skipTests
// true 跳过测试
const skipTests = args.skipTests
// 对应 yarn run release --skipBuild
// true
const skipBuild = args.skipBuild
// 读取 packages 文件夹,过滤掉 不是 .ts文件 结尾 并且不是 . 开头的文件夹
const packages = fs
.readdirSync(path.resolve(__dirname, '../packages'))
.filter(p => !p.endsWith('.ts') && !p.startsWith('.'))
// 跳过的包
const skippedPackages = []
// 版本递增
const versionIncrements = [
'patch',
'minor',
'major',
...(preId ? ['prepatch', 'preminor', 'premajor', 'prerelease'] : [])
]
接着来
2.2.2
const inc = i => semver.inc(currentVersion, i, preId)
// 协助理解,也可查看semver学习 https://github.com/npm/node-semver#prerelease-identifie
// semver.inc('3.2.4', 'prerelease', 'beta')
// 3.2.5-beta.0
// 获取 node_modules/.bin/ 目录下的命令
// eg: bin('jest') 相当于在命令终端,项目根目录 运行 ./node_modules/.bin/jest 命令
const bin = name => path.resolve(__dirname, '../node_modules/.bin/' + name)
// 在终端跑真实命令 npm run build --release
const run = (bin, args, opts = {}) => execa(bin, args, { stdio: 'inherit', ...opts })
// 不跑真实命令,只是 console.log(); 打印 'yarn build --release'
const dryRun = (bin, args, opts = {}) => console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts)
// 是否真实跑命令
const runIfNotDry = isDryRun ? dryRun : run
// 获取packages下对应包的路径
const getPkgRoot = pkg => path.resolve(__dirname, '../packages/' + pkg)
// 控制台输出
const step = msg => console.log(chalk.cyan(msg))
3、接下来看主流程main函数
const chalk = require('chalk')
const step = msg => console.log(chalk.cyan(msg))
// 前面一堆依赖引入和函数定义等
async function main(){
// 版本校验
// run tests before release
step('\nRunning tests...')
// update all package versions and inter-dependencies
step('\nUpdating cross dependencies...')
// build all packages with types
step('\nBuilding all packages...')
// generate changelog
step('\nCommitting changes...')
// publish packages
step('\nPublishing packages...')
// push to GitHub
step('\nPushing to GitHub...')
}
main().catch(err => {
console.error(err)
})
去掉具体的一些方法实现后,可以看出main函数流程包括这么几步
3.1收看看一下test之前的一段代码
这段代码看起来很长,但功能很简单就是与用户交互选择对应的发布版本
结合图片一起观察
对应代码:
let targetVersion = args._[0]
if (!targetVersion) {
// no explicit version, offer suggestions
const { release } = await prompt({
type: 'select',
name: 'release',
message: 'Select release type',
choices: versionIncrements.map(i => `${i} (${inc(i)})`).concat(['custom'])
})
if (release === 'custom') {
targetVersion = (
await prompt({
type: 'input',
name: 'version',
message: 'Input custom version',
initial: currentVersion
})
).version
} else {
targetVersion = release.match(/\((.*)\)/)[1]
}
}
if (!semver.valid(targetVersion)) {
throw new Error(`invalid target version: ${targetVersion}`)
}
const { yes } = await prompt({
type: 'confirm',
name: 'yes',
message: `Releasing v${targetVersion}. Confirm?`
})
if (!yes) {
return
}
3.2 step('\nRunning tests...')代码
jest执行测试
if (!skipTests && !isDryRun) {
await run(bin('jest'), ['--clearCache'])
await run('yarn', ['test', '--bail'])
} else {
console.log(`(skipped)`)
}
3.3 step('\nUpdating cross dependencies...') 更新依赖
updateVersions(targetVersion)
function updateVersions(version) {
// 1. update root package.json
updatePackage(path.resolve(__dirname, '..'), version)
// 2. update all packages
packages.forEach(p => updatePackage(getPkgRoot(p), version))
}
function updatePackage(pkgRoot, version) {
const pkgPath = path.resolve(pkgRoot, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
pkg.version = version
updateDeps(pkg, 'dependencies', version)
updateDeps(pkg, 'peerDependencies', version)
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
}
function updateDeps(pkg, depType, version) {
const deps = pkg[depType]
if (!deps) return
Object.keys(deps).forEach(dep => {
if (
dep === 'vue' ||
(dep.startsWith('@vue') && packages.includes(dep.replace(/^@vue\//, '')))
) {
console.log(
chalk.yellow(`${pkg.name} -> ${depType} -> ${dep}@${version}`)
)
deps[dep] = version
}
})
}
3.4 打包,生成changelog
if (!skipBuild && !isDryRun) {
await run('yarn', ['build', '--release'])
// test generated dts files
step('\nVerifying type declarations...')
await run('yarn', ['test-dts-only'])
} else {
console.log(`(skipped)`)
}
// generate changelog
await run(`yarn`, ['changelog'])
const { stdout } = await run('git', ['diff'], { stdio: 'pipe' })
if (stdout) {
step('\nCommitting changes...')
await runIfNotDry('git', ['add', '-A'])
await runIfNotDry('git', ['commit', '-m', `release: v${targetVersion}`])
} else {
console.log('No changes to commit.')
}
请看下图:
3.5 step('\nPublishing packages...') 发布
for (const pkg of packages) {
await publishPackage(pkg, targetVersion, runIfNotDry)
}
async function publishPackage(pkgName, version, runIfNotDry) {
if (skippedPackages.includes(pkgName)) {
return
}
const pkgRoot = getPkgRoot(pkgName)
const pkgPath = path.resolve(pkgRoot, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
if (pkg.private) {
return
}
// For now, all 3.x packages except "vue" can be published as
// `latest`, whereas "vue" will be published under the "next" tag.
let releaseTag = null
if (args.tag) {
releaseTag = args.tag
} else if (version.includes('alpha')) {
releaseTag = 'alpha'
} else if (version.includes('beta')) {
releaseTag = 'beta'
} else if (version.includes('rc')) {
releaseTag = 'rc'
} else if (pkgName === 'vue') {
// TODO remove when 3.x becomes default
releaseTag = 'next'
}
// TODO use inferred release channel after official 3.0 release
// const releaseTag = semver.prerelease(version)[0] || null
step(`Publishing ${pkgName}...`)
try {
await runIfNotDry(
'yarn',
[
'publish',
'--new-version',
version,
...(releaseTag ? ['--tag', releaseTag] : []),
'--access',
'public'
],
{
cwd: pkgRoot,
stdio: 'pipe'
}
)
console.log(chalk.green(`Successfully published ${pkgName}@${version}`))
} catch (e) {
if (e.stderr.match(/previously published/)) {
console.log(chalk.red(`Skipping already published: ${pkgName}`))
} else {
throw e
}
}
}
执行命令后如图所示:
3.6 step('\nPushing to GitHub...') 发布
将对应代码推送至github
await runIfNotDry('git', ['tag', `v${targetVersion}`])
await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
await runIfNotDry('git', ['push'])
至此,本次源码解读完毕!想要参加源码阅读的可留言,我带你直飞