feat(build): 添加自动更新package.json时间戳的vite插件

添加updatePackageJson插件,在构建时自动更新package.json中的时间戳字段
This commit is contained in:
feige996 2025-06-17 18:09:51 +08:00
parent f2119f3f73
commit f6208a191d
3 changed files with 34 additions and 0 deletions

View File

@ -0,0 +1,31 @@
// src/plugins/updatePackageJson.ts
import { Plugin } from 'vite'
import fs from 'fs/promises'
import path from 'path'
const updatePackageJson = (): Plugin => {
return {
name: 'update-package-json',
async buildStart() {
const packageJsonPath = path.resolve(process.cwd(), 'package.json')
try {
// 读取并解析 package.json
const content = await fs.readFile(packageJsonPath, 'utf-8')
const packageJson = JSON.parse(content)
// 更新时间戳(使用 ISO 格式或自定义格式)
packageJson['update-time'] = new Date().toISOString().split('T')[0] // YYYY-MM-DD
// 写回文件(保持 2 空格缩进)
await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n', 'utf-8')
console.log(`[update-package-json] 更新时间戳: ${packageJson['update-time']}`)
} catch (error) {
console.error('[update-package-json] 插件执行失败:', error)
}
},
}
}
export default updatePackageJson

View File

@ -44,6 +44,7 @@
}
]
},
"__esModule": true,
"pages": [
{
"path": "pages/index/index",

View File

@ -21,6 +21,7 @@ import AutoImport from 'unplugin-auto-import/vite'
import ViteRestart from 'vite-plugin-restart'
import { copyNativeRes } from './vite-plugins/copyNativeRes'
import Components from '@uni-helper/vite-plugin-uni-components'
import updatePackageJson from './scripts/updatePackageJson'
// https://vitejs.dev/config/
export default async ({ command, mode }) => {
@ -129,6 +130,7 @@ export default async ({ command, mode }) => {
dts: 'src/types/components.d.ts', // 自动生成的组件类型声明文件路径(用于 TypeScript 支持)
}),
Uni(),
updatePackageJson(),
],
define: {
__UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),