vite或webpack前端输出git提交版本号
背景
定位当前前端的版本对应git上的哪个版本,以方便定位问题和版本发布
具体实现
- 获取版本号
const { execSync } = require('child_process');
const gitVersion = execSync('git rev-parse --short HEAD').toString().trim();
vite 打包方式
- 在vite 中定义全部变量
export default defineConfig({
define: {
__APP_VERSION__: gitVersion,
},
})
- 在 env.d.ts 或 vite-env.d.ts 文件中添加类型声明,以获得类型检查以及代码提示
// vite-env.d.ts
declare const __APP_VERSION__: string
webpack 打包方式
let webpack = require("webpack");
module.exports = {
plugins: [
new webpack.DefinePlugin({
__APP_VERSION__: gitVersion
})
]
}
使用
在项目任意位置,如在main.ts 等等
console.log(__APP_VERSION__)