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_' }),
],
})
2
Answers
In
VITE
project you should import env fromimport.meta.VITE_API_KEY
Remember! : While use VITE project your all
env variables
names are starting withVITE
for example:
VITE_API_KEY =randomKey ✅
API_KEY = randomKey ❌
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: