获取项目版本
使用shelljs模块,读取git的tag信息,获取项目的版本号,开发环境使用commit哈希值,生产环境使用tag。
实现源码
ts
import shelljs from 'shelljs';
const { exec, which, echo } = shelljs;
const getLatestCommit = () => {
const currentBranch = exec('git symbolic-ref --short -q HEAD', {
silent: true
}).stdout;
const latestCommit = exec('git rev-parse --short HEAD', {
silent: true
}).stdout;
return `${currentBranch.replace(/\n/g, '')}-${latestCommit.replace(
/\n/g,
''
)}`;
};
const getLatestVersion = () => {
if (!which('git')) {
echo('Sorry, this script requires git.');
return '';
}
if (process.env.NODE_ENV !== 'production') {
return getLatestCommit();
}
let versionInfo = exec('git describe --abbrev=0 --tags', {
silent: true
}).stdout;
if (!versionInfo) {
return getLatestCommit();
}
const versions = versionInfo.split('\n');
return versions[versions.length - 2];
};
const version = `"${getLatestVersion()}"`;
export default version;安装
需要安装shelljs、@types/shelljs模块。
bash
pnpm add shelljs @types/shelljs -D在 vite.config.ts 中使用
ts
import version from 'version.ts'
import { defineConfig } from 'vite'
export default defineConfig({
define: {
__APP_VERSION__: version
}
})