Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add commit hash into reactjs vite.config.js

Tags:

reactjs

vite

I want to add commit hash into my react app. Normally, I added it with webpack but this project they are using vite.config.js. May I know how to inject commit hash into vite and how can I use it in react component.

Thanks.

const commitHash = require('child_process').execSync('git rev-parse --short HEAD').toString();

like image 842
Alex Aung Avatar asked Apr 15 '26 23:04

Alex Aung


2 Answers

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

const commitHash = require('child_process')
    .execSync('git rev-parse --short HEAD')
    .toString();

export default defineConfig({
  define: {
    __COMMIT_HASH__: JSON.stringify(commitHash),
  },
  plugins: [react()],
});
like image 188
Alex Aung Avatar answered Apr 17 '26 13:04

Alex Aung


Here's an alternative to the dynamic require

import * as child from "child_process";

const commitHash = child.execSync("git rev-parse --short HEAD").toString();
like image 31
Jonathan Ward Avatar answered Apr 17 '26 12:04

Jonathan Ward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!