I am using vitejs to compile my react app statically, however after build .env imports become undefined which is not the case on development stage.
reading the docs I've found out that these variables are replace by their corresponding values, but upon looking at the source/compiled code in the dev tools after serving it shows an empty object with the env name/key
i might have a wrong configuration in vite.config.ts so here it is.
//vite.config.ts
import { defineConfig, loadEnv } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import { getAliases } from 'vite-aliases';
const aliases = getAliases({
path: 'src',
prefix: '@',
});
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };
// import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
// import.meta.env.VITE_PORT available here with: process.env.VITE_PORT
const plugins = mode === 'development' ? [reactRefresh()] : [];
return defineConfig({
plugins,
publicDir: 'src/assets',
resolve: {
alias: aliases,
},
build: {
chunkSizeWarningLimit: 1500,
},
});
};
And also the code where I'm referencing these env var
//config.ts
export const config = () => {
const url = import.meta.env.VITE_SERVER_URL;
const api = import.meta.env.VITE_API_ENDPOINT;
const auth = import.meta.env.VITE_AUTH_ENDPOINT;
const isProd = import.meta.env.MODE === 'production';
const isDev = import.meta.env.MODE === 'development';
console.log(url, api, auth);
return {
api: (endpoint: string) => `${url}${api}${endpoint}`,
auth: (endpoint: string) => `${url}${auth}${endpoint}`,
test: (endpoint: string) => `${url}test${endpoint}`,
isProd,
isDev,
};
};