Search code examples
javascriptgitversion-controlvite

How to insert git info in environment variables using Vite?


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


Solution

  • 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.