Vite Plugin Git Commit Hash
raw JSON → 1.0.7 verified Mon Apr 27 auth: no javascript
A Vite plugin that injects the latest Git commit hash as a global `GIT_COMMIT_HASH` variable at build time. Current stable version is 1.0.7, released under MIT license. It is lightweight, has zero runtime dependencies (only peer dependency on Vite >=3), and ships TypeScript declarations. The plugin is ESM and CommonJS compatible. Key differentiator: it provides a simple, declarative way to expose git hash without complex build scripts or environment variables.
Common errors
error Cannot find name 'GIT_COMMIT_HASH'. Do you need to add a type declaration? ↓
cause The global variable GIT_COMMIT_HASH is not recognized by TypeScript without a declaration.
fix
Add
declare const GIT_COMMIT_HASH: string; to a .d.ts file (e.g., env.d.ts). error GIT_COMMIT_HASH is not defined ↓
cause The plugin may not be running or the variable is not replaced correctly in development mode.
fix
Ensure the plugin is added to the Vite config's plugins array. In development, consider that GIT_COMMIT_HASH is replaced only after build.
Warnings
breaking Plugin uses Vite's define() which replaces global identifiers literally. If your code uses a variable named GIT_COMMIT_HASH for another purpose, it will be overwritten. ↓
fix Avoid using GIT_COMMIT_HASH as a variable name elsewhere, or use a different config option (if available).
gotcha GIT_COMMIT_HASH is only available after build, not during development server (HMR) unless manually configured. ↓
fix Check process.env.NODE_ENV or use Vite's import.meta.env.DEV to conditionally access the hash.
gotcha The plugin requires Vite >=3. Older Vite versions will cause errors. ↓
fix Upgrade Vite to version 3 or higher.
Install
npm install vite-plugin-git-commit-hash yarn add vite-plugin-git-commit-hash pnpm add vite-plugin-git-commit-hash Imports
- gitCommitHashPlugin wrong
import gitCommitHashPlugin from 'vite-plugin-git-commit-hash'correctimport { gitCommitHashPlugin } from 'vite-plugin-git-commit-hash' - GIT_COMMIT_HASH wrong
import { GIT_COMMIT_HASH } from 'vite-plugin-git-commit-hash'correctconsole.log(GIT_COMMIT_HASH); // global variable - type GIT_COMMIT_HASH wrong
import type { GIT_COMMIT_HASH } from 'vite-plugin-git-commit-hash'correctdeclare const GIT_COMMIT_HASH: string; // in a .d.ts file
Quickstart
// vite.config.ts
import { defineConfig } from 'vite';
import { gitCommitHashPlugin } from 'vite-plugin-git-commit-hash';
export default defineConfig({
plugins: [gitCommitHashPlugin()],
});
// main.ts
console.log(`App version: ${GIT_COMMIT_HASH}`);