Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing build date with Vite + React

Im trying to log build date for my React+Vite app. All i need is something like this in my index.html:

<script>console.log(__BUILD_DATE__);</script>

and __BUILD_DATE__ replaced with build time string on build

like image 737
kabukiman Avatar asked Mar 22 '26 14:03

kabukiman


2 Answers

The other answers pretty much already cover it, but I want to add a few more details since it was confusing to me and I didn't find any other Stackoverflow pages on this subject.

First - read the Vite documentation on define and environment variables.

Second - if you want to make a constant that you can access in your application, do what the others said above. Put a uniquely named variable in the define section of your vite config file:

define: {
  BUILD_DATE: JSON.stringify(new Date().toISOString())
}

And then in your vite-env.d.ts or env.d.ts file put this:

declare const BUILD_DATE: string;

And in your app you can use the BUILD_DATE variable, it doesn't need to be imported.

Third - if you prefer to set a custom or dynamic environment variable in your vite config file (rather than in a .env file) you can do this:

define: {
  'import.meta.env.VITE_BUILD_DATE': JSON.stringify(new Date().toISOString())
}

Then in your vite-env.d.ts or env.d.ts file you can define that value:

interface ImportMetaEnv {
  readonly VITE_BUILD_DATE: string;
}

And then in your code you can access that environment variable as you normally would in a vite app - import.meta.env.VITE_BUILD_DATE.

If you wanted to access an environment variable in your index.html file, you can also do this:

<div>%VITE_BUILD_DATE%</div>
like image 134
ccallendar Avatar answered Mar 24 '26 03:03

ccallendar


You can try config on file vite.config.ts :

define: {
   BUILD_TIMESTAMP: new Date(),
},
like image 24
Bình Lê Đức Avatar answered Mar 24 '26 04:03

Bình Lê Đức



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!