xlian-version-plugin
v0.0.20
Published
xlian
Readme
xlian-version-plugin (Vite 插件)
简短说明
这是一个 Vite 插件,用于在构建开始时生成一个 public/v.json 文件,包含构建时间戳、版本号(从 .env 的 VITE_APP_VERSION 读取)和 git 短 hash(若可用)。
安装
- 若作为本地插件,无需安装,直接从项目路径引入。
- 若发布为 npm 包:
- npm:
npm i xlian-version-plugin - yarn:
yarn add xlian-version-plugin - pnpm:
pnpm add xlian-version-plugin
- npm:
配置与引入(示例)
通过本地文件引入(项目 ESM 环境):
// filepath: /Users/mit-xl/code/version-plugin/README.md import xlianVersionPlugin from './index.js'; // 相对路径指向本插件的 index.js export default { // ...existing code... plugins: [ xlianVersionPlugin(), // ...existing plugins... ], // ...existing code... }通过 npm 包引入(包名为
xlian-version-plugin):// filepath: /Users/mit-xl/code/version-plugin/README.md // CommonJS 环境(推荐,插件以 CommonJS 导出) const xlianVersionPlugin = require('xlian-version-plugin'); module.exports = { // ...existing code... plugins: [ xlianVersionPlugin() ], // ...existing code... }
.env 配置
在项目根目录创建 .env 或 .env.local,添加:
VITE_APP_VERSION=1.2.3插件会读取该变量并写入到 public/v.json 的 version 字段。
输出文件示例(public/v.json)
{
"timestamp": "2025-09-03 14-30-00",
"version": "1.2.3",
"hash": "a1b2c3d"
}字段说明
timestamp: 本地化格式的构建时间字符串(zh-CN),用于显示或追踪构建时间。version: 来自环境变量VITE_APP_VERSION。hash: git 短 hash;若无法通过 git 获取,将为空字符串,插件会在控制台打印警告。
注意事项
- 插件使用
dotenv读取环境变量,请确保在运行时存在.env(或通过其他方式设置VITE_APP_VERSION)。 - 获取 git hash 依赖于本地 git 可用性,CI 环境请确保安装并初始化 git 或提供其他机制。
- 文件写入目标为项目的
public/v.json,若不存在目录会自动创建。 - 该插件为 CommonJS 模块(使用
module.exports),在 ESM 项目中若需使用import,可以通过构建工具的兼容配置或在项目 package.json 设置"type": "module"并使用默认导入互操作处理。
示例(完整的 vite.config.js 最小示例)
// filepath: /Users/mit-xl/code/version-plugin/README.md
import { defineConfig } from 'vite';
import xlianVersionPlugin from './index.js';
export default defineConfig({
plugins: [xlianVersionPlugin()],
});运行 package.json 中脚本(例如测试)
- npm:
npm test - yarn:
yarn test - pnpm:
pnpm test
许可证与贡献
可在此处补充许可证与贡献说明(如 MIT、PR 欢迎等)。
