6

How to get information from git about current branch, commit date and other when using Vite bundler?

1 Answer 1

11

It is possible to use execSync and retrive git information when starting Vite.
vite.config.ts:

export default ({ mode }: ConfigEnv) => {
   const dev = mode === 'development';

   const commitDate = execSync('git log -1 --format=%cI').toString().trimEnd();
   const branchName = execSync('git rev-parse --abbrev-ref HEAD').toString().trimEnd();
   const commitHash = execSync('git rev-parse HEAD').toString().trimEnd();
   const lastCommitMessage = execSync('git show -s --format=%s').toString().trimEnd();

   process.env.VITE_GIT_COMMIT_DATE = commitDate;
   process.env.VITE_GIT_BRANCH_NAME = branchName;
   process.env.VITE_GIT_COMMIT_HASH = commitHash;
   process.env.VITE_GIT_LAST_COMMIT_MESSAGE = lastCommitMessage;
...

NB: It is important to use VITE_ prefix in variables, otherwise they won't be avaiable.

Usage example:

function BuildInfo() {
   const date = new Date(import.meta.env.VITE_GIT_COMMIT_DATE);
   return (
      <div>
         <span>{date.toLocaleString()}</span>
         <span>{import.meta.env.VITE_GIT_LAST_COMMIT_MESSAGE}</span>
         <span>{import.meta.env.VITE_GIT_BRANCH_NAME}/{import.meta.env.VITE_GIT_COMMIT_HASH}</span>
      </div>
   );
}

UPD: You can also use https://www.npmjs.com/package/git-rev-sync to get git information.

1
  • 3
    does this work for vite build? thanks,
    – Xb74Dkjb
    Commented Jan 18, 2023 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.