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.

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.
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.
npm install vite-plugin-git-commit-hash
yarn add vite-plugin-git-commit-hash
pnpm add vite-plugin-git-commit-hash

Shows how to add the plugin to Vite config and use the global GIT_COMMIT_HASH variable in your code.

// 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}`);