自定义版本文件与非 Npm 项目
@neosjs/release 不强依赖 package.json:当目录中没有 package.json(或通过 npm: false 禁用)时,内置的 git、changelog、github、gitlab、pr、version 插件依然可以独立工作。
下面展示两种最常见的自定义版本管理方案。
方案一:编写本地插件接管独立版本文件(如 VERSION / pyproject.toml / Cargo.toml)
当项目没有 package.json,而是通过独立文件(例如根目录的 VERSION 文件)保存版本号时,只需编写一个十几行的本地插件。
1. 创建 ./scripts/version-file-plugin.mjs
js
import fs from 'node:fs'
import { Plugin } from '@neosjs/release'
export default class VersionFilePlugin extends Plugin {
static disablePlugin() {
// 禁用内置 npm 插件(若目录无 package.json 本身也不会启用)
return ['npm']
}
get filePath() {
return this.options.file || 'VERSION'
}
getLatestVersion() {
if (!fs.existsSync(this.filePath)) return null
return fs.readFileSync(this.filePath, 'utf8').trim()
}
bump(version) {
if (this.config.isDryRun) return
fs.writeFileSync(this.filePath, `${version}\n`, 'utf8')
}
}2. 在 release.config.ts 中启用
ts
import { defineConfig } from '@neosjs/release'
export default defineConfig({
plugins: {
'./scripts/version-file-plugin.mjs': {
file: 'VERSION'
}
},
git: {
commitMessage: 'chore: release v${version}',
tagName: 'v${version}',
push: true
},
github: {
release: true
}
})因为外部插件的 getLatestVersion() 和 bump() 均在内置插件之前执行:
getLatestVersion()会优先读取VERSION中的版本号;bump(version)写入新版本后,内置git插件会在beforeRelease自动将其暂存并随CHANGELOG.md一起提交(前提是VERSION已被 Git 跟踪;若为新建文件请开启git.addUntrackedFiles: true或在插件中调用await this.exec(['git', 'add', this.filePath]))。
方案二:使用 after:bump 钩子同步多文件版本号
如果项目仍以 package.json 为主版本源,但希望发版时把版本号同步写入额外文件(例如 src/version.ts、manifest.json 或子包清单),直接借助 after:bump 钩子即可:
scripts/sync-version.mjs:
js
import fs from 'node:fs'
const version = process.argv[2]
if (!version) {
console.error('缺少版本号参数')
process.exit(1)
}
fs.writeFileSync('src/version.ts', `export const VERSION = '${version}'\n`, 'utf8')release.config.ts:
ts
import { defineConfig } from '@neosjs/release'
export default defineConfig({
hooks: {
// 在 git 暂存与提交之前运行,因此对已跟踪文件的改动会自动纳入本次发版提交
'after:bump': 'node ./scripts/sync-version.mjs ${version}'
}
})如果同步脚本还会修改新建的未跟踪文件,记得在配置中开启 git.addUntrackedFiles: true,或在脚本末尾自行执行 git add。