vite-plugin-detect-prepare
v1.0.7
Published
A Vite plugin that detects git branch and sets custom environment variables
Maintainers
Readme
vite-plugin-detect-prepare
一个检测 git 分支并设置自定义环境变量的 Vite 插件。
✨ 特性
- 🔍 检测当前 git 分支
- 🎯 根据分支设置环境变量
- 🚀 支持字符串和正则表达式匹配
- ⚡ 轻量级,零依赖
- 🛠️ TypeScript 支持
📦 安装
# npm
npm install vite-plugin-detect-prepare -D
# yarn
yarn add vite-plugin-detect-prepare -D
# pnpm
pnpm add vite-plugin-detect-prepare -D🚀 使用方法
基础用法
import { defineConfig } from 'vite'
import detectPrepare from 'vite-plugin-detect-prepare'
export default defineConfig({
plugins: [
detectPrepare()
]
})自定义配置
import { defineConfig } from 'vite'
import detectPrepare from 'vite-plugin-detect-prepare'
export default defineConfig({
plugins: [
detectPrepare({
targetBranch: 'pre-release',
envVarName: 'VITE_IS_PRERELEASE'
})
]
})使用正则表达式
import { defineConfig } from 'vite'
import detectPrepare from 'vite-plugin-detect-prepare'
export default defineConfig({
plugins: [
detectPrepare({
targetBranch: /-pre-/,
envVarName: 'VITE_PRE_ENVIRONMENT'
})
]
})⚙️ 配置项
| 选项 | 类型 | 默认值 | 说明 |
| ------------ | ----------------- | -------------------- | ------------------------------ |
| targetBranch | string\|RegExp | 'prepare' | 需要检测的分支名或正则表达式 |
| envVarName | string | 'VITE_PRE_RELEASE' | 设置的环境变量名 |
📖 示例
检测预发布分支
// vite.config.js
export default defineConfig({
plugins: [
detectPrepare({
targetBranch: /-(pre|beta|alpha)-/,
envVarName: 'VITE_IS_PRERELEASE'
})
]
})在你的应用中使用:
// main.js
if (import.meta.env.VITE_IS_PRERELEASE === 'true') {
console.log('当前为预发布环境')
// 启用调试功能
window.__DEBUG__ = true
}Vue 项目中的使用
<template>
<div>
<div v-if="isPreRelease" class="pre-release-banner">
⚠️ 预发布版本
</div>
<!-- 其他内容 -->
</div>
</template>
<script setup>
const isPreRelease = import.meta.env.VITE_PRE_RELEASE === 'true'
</script>React 项目中的使用
function App() {
const isPreRelease = import.meta.env.VITE_PRE_RELEASE === 'true'
return (
<div>
{isPreRelease && (
<div className="pre-release-banner">
⚠️ 预发布版本
</div>
)}
{/* 其他内容 */}
</div>
)
}🔧 工作原理
- 插件在构建时读取当前 git 分支信息
- 根据配置的
targetBranch进行匹配 - 如果匹配成功,设置对应的环境变量为
'true' - 如果不匹配,设置环境变量为
'false'
📝 注意事项
- 环境变量只在构建时确定,运行时不会动态变化
- 确保项目在 git 仓库中,否则无法检测分支信息
- 环境变量名必须以
VITE_开头才能在客户端代码中访问
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📄 许可证
MIT © [Your Name]
🔗 相关链接
如果这个插件对你有帮助,请给个 ⭐ 支持一下!
