vue3.2 是怎么发布的 vue-release
前言
vue 发版是怎么做的,首先看看 vue 的源码库的脚手架常用依赖库有哪些
chalk
:终端显示颜色
conventional-changelog-cli
:生成 commit 日志的 cli
csstype
:css 的 ts 类型提示
enquirer
:输入的选择,问题选择器
execa
:执行 shell 脚本
fs-extra
:对 fs 的扩展
marked
:md 的文档解析器
minimist
:取命令行参数
npm-run-all
:可以运行多个命令
pug
:模板
puppeteer
:无头浏览器
semver
:包版本检查器
serve
:起一个静态服务
simple-git-hooks
:一个轻松管理 git hooks 的工具
terser
:es6 的编译器
brotli
:解码
zlib
:压缩
vue/core 包
使用pnpm
做的monorepo
包管理
查看 scripts 脚本,有以下文件
preinstall.js
js
if (!/pnpm/.test(process.env.npm_execpath || '')) {
console.warn(
`\u001b[33mThis repository requires using pnpm as the package manager ` +
` for scripts to work properly.\u001b[39m\n`,
)
process.exit(1)
}
在下载之前验证是否是pnpm
如果不是直接爆出警告并退出当前进程
release.js 发版的主要脚本
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')
// 执行shell命令
const execa = require('execa')
// 生成一个唯一id
const preId =
args.preid || (semver.prerelease(currentVersion) && semver.prerelease(currentVersion)[0])
const isDryRun = args.dry
const skipTests = args.skipTests
const skipBuild = args.skipBuild
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'] : []),
]
// 计算出一个版本号
const inc = (i) => semver.inc(currentVersion, i, preId)
// 可执行的shell命令
const bin = (name) => path.resolve(__dirname, '../node_modules/.bin/' + name)
// 执行命令函数
const run = (bin, args, opts = {}) => execa(bin, args, { stdio: 'inherit', ...opts })
const dryRun = (bin, args, opts = {}) =>
console.log(chalk.blue(`[dryrun] ${bin} ${args.join(' ')}`), opts)
const runIfNotDry = isDryRun ? dryRun : run
const getPkgRoot = (pkg) => path.resolve(__dirname, '../packages/' + pkg)
const step = (msg) => console.log(chalk.cyan(msg))
// 主函数
async function main() {
// 获取当前版本号
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
}
// run tests before release
step('\nRunning tests...')
if (!skipTests && !isDryRun) {
await run(bin('jest'), ['--clearCache'])
await run('pnpm', ['test', '--bail'])
} else {
console.log(`(skipped)`)
}
// update all package versions and inter-dependencies
step('\nUpdating cross dependencies...')
updateVersions(targetVersion)
// build all packages with types
step('\nBuilding all packages...')
if (!skipBuild && !isDryRun) {
await run('pnpm', ['run', 'build', '--release'])
// test generated dts files
step('\nVerifying type declarations...')
await run('pnpm', ['run', 'test-dts-only'])
} else {
console.log(`(skipped)`)
}
// generate changelog
step('\nGenerating changelog...')
await run(`pnpm`, ['run', 'changelog'])
// update pnpm-lock.yaml
step('\nUpdating lockfile...')
await run(`pnpm`, ['install', '--prefer-offline'])
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.')
}
// publish packages
step('\nPublishing packages...')
for (const pkg of packages) {
await publishPackage(pkg, targetVersion, runIfNotDry)
}
// push to GitHub
step('\nPushing to GitHub...')
await runIfNotDry('git', ['tag', `v${targetVersion}`])
await runIfNotDry('git', ['push', 'origin', `refs/tags/v${targetVersion}`])
await runIfNotDry('git', ['push'])
if (isDryRun) {
console.log(`\nDry run finished - run git diff to see package changes.`)
}
if (skippedPackages.length) {
console.log(
chalk.yellow(
`The following packages are skipped and NOT published:\n- ${skippedPackages.join('\n- ')}`,
),
)
}
console.log()
}
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
}
})
}
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
}
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'
}
step(`Publishing ${pkgName}...`)
try {
await runIfNotDry(
// note: use of yarn is intentional here as we rely on its publishing
// behavior.
'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
}
}
}
main().catch((err) => {
updateVersions(currentVersion)
console.error(err)
})