I'm trying to access an env variable from my index.html file.
The code below seems to work in CRA but doesnt work with my vite, react project setup
const APP_ID = '%REACT_APP_ID%'
    <script>
      //Set your APP_ID
      const APP_ID = '%REACT_APP_ID%'
     ....
    </script>
my vite config file
import { defineConfig, splitVendorChunkPlugin } from 'vite'
import react from '@vitejs/plugin-react'
import EnvironmentPlugin from 'vite-plugin-environment'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    splitVendorChunkPlugin(),
    react(),
    EnvironmentPlugin('all', { prefix: 'REACT_APP_' }),
  ],
})
Replacing environment variables in HTML files is supported since Vite 4.2.0.
Define environment variables with the VITE_ prefix, and wrap it between % in the HTML file.
For example:
<div>%VITE_SOME_KEY%</div>
You should to use only "%YOUR_VAR%" like this:
<script type="text/javascript">
    const flag = "%VITE_TRACKING_ID%" 
          if (flag) {
            ...
</script>
have in mind you would need to update your Vite 4.2.0 as commented @Unmitigated
this is the thread to fix https://github.com/vitejs/vite/issues/3105#issuecomment-1441947641
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