Skip to content

Astro Git Version Integration

This document explains how to show the current git version in an Astro/Starlight website.

Method 1: Build Script with Environment Variable

Section titled “Method 1: Build Script with Environment Variable”

The most reliable way to show the git version in an Astro site is to:

  1. Generate a version file during the build process
  2. Import the version file in your Astro components

Create scripts/generate-version.mjs:

import { writeFileSync } from 'fs';
import { execSync } from 'child_process';
const gitVersion = execSync('git describe --tags --always --dirty').toString().trim();
const versionData = `export const GIT_VERSION = '${gitVersion}';\n`;
writeFileSync('src/env/version.ts', versionData);
console.log(`Generated version: ${gitVersion}`);

Add the version generation to the build process:

import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
// ... other config
hooks: {
'astro:config:setup': async ({ command, config, injectScript, updateConfig }) => {
// Generate version file before build
if (command === 'build') {
const { execSync } = await import('child_process');
const gitVersion = execSync('git describe --tags --always --dirty').toString().trim();
const versionData = `export const GIT_VERSION = '${gitVersion}';\n`;
await import('fs').then(fs => fs.writeFileSync('src/env/version.ts', versionData));
}
},
},
});

Create src/components/GitVersion.astro:

---
import { GIT_VERSION } from '../env/version.ts';
---
<span class="git-version" title="Git version">v{GIT_VERSION}</span>

Include the GitVersion component in your Starlight footer or layout.

Method 2: Using Import Meta Env (Development Only)

Section titled “Method 2: Using Import Meta Env (Development Only)”

In development, you can use import.meta.env but this doesn’t work for git version since it’s not an environment variable.

Create a static version.json file and update it manually or via CI/CD:

{
"version": "v1.0.0-2-g3b08d32",
"commit": "3b08d32",
"tag": "v1.0.0",
"dirty": false
}

Then import it in your Astro components:

---
import version from '../../public/version.json' assert { type: 'json' };
---
<span class="git-version">v{version.version}</span>

For the Learn Project, use Method 1 with a build script that generates src/env/version.ts during the build process. This ensures the git version is always up-to-date with the current commit.

  1. Create scripts/generate-version.mjs
  2. Update astro.config.mjs to run the script before build
  3. Create src/env/version.ts (generated)
  4. Create src/components/GitVersion.astro
  5. Add to Starlight footer or layout