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
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>
You can try config on file vite.config.ts :
define: {
BUILD_TIMESTAMP: new Date(),
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With