I am trying to interpolate environment variables in the index.html
of my React app using vite
, however, I am getting the following error:
(!) %REACT_APP_BACKEND_URL% is not defined in env variables found in /index.html. Is the variable mistyped?
This is a sample of my configuration file:
/* eslint-disable import/extensions */
/* eslint-disable import/no-extraneous-dependencies */
import { defineConfig, loadEnv } from 'vite'
import svgr from 'vite-plugin-svgr'
import tsconfigPaths from 'vite-tsconfig-paths'
import react from '@vitejs/plugin-react'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), 'REACT_APP_')
const processEnvValues = {
'process.env': Object.entries(env).reduce(
(prev, [key, val]) => ({
...prev,
[key]: val
}),
{}
)
}
return {
define: processEnvValues,
root: 'src',
build: {
// Relative to the root
outDir: '../dist'
},
envPrefix: 'REACT_APP_',
base: './',
plugins: [
react(),
svgr(),
tsconfigPaths({
root: '../'
}),
],
publicDir: '../public'
}
})
And this is my index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="refferer" content="strict-origin-when-cross-origin" />
<link rel="dns-prefetch" href="%REACT_APP_BACKEND_URL%" />
</head>
<body>
<div class="ac-content">
<noscript> You need to enable JavaScript to run this app. </noscript>
<div id="root"></div>
<script type="module" src="index.jsx"></script>
</div>
</body>
</html>
I am loading the env
vars from .env.development.local
and I can log them using console.log({ processEnvValues })