Environment variables are critical for setting configuration parameters that adapt as environments switch between development, testing, and production. Managing these variables in a robust, scalable way ensures smooth development, deployment, and maintenance. It benefits both developers working on the code and DevOps engineers building CI/CD pipelines.
Here, I propose an approach to minimize code duplication and maintenance effort while adhering to the principles of Don't Repeat Yourself (DRY) and Keep It Simple, Stupid (KISS). Additionally, I’ll outline alternative strategies with their pros and cons.
VITE_API_URL_DEV=http://localhost:3000/v1 VITE_BRAND_NAME_DEV=TablesXi VITE_API_URL_PROD=https://api.prod.com/v1 VITE_BRAND_NAME_PROD=TablesXi VITE_MODE=dev
export const ENV_VARS = { VITE_API_URL: "VITE_API_URL", VITE_BRAND_NAME: "VITE_BRAND_NAME", };
const environmentMode = import.meta.env.VITE_MODE; export const getEnvVar = (key) => { const mode = environmentMode === "dev" ? "_DEV" : "_PROD"; return import.meta.env[`${key}${mode}`]; };
const apiUrl = getEnvVar(ENV_VARS.VITE_API_URL);
Advantages:
Disadvantages:
const config = environmentMode === "dev" ? require("./config.dev") : require("./config.prod"); export default config;
Pros:
Cons:
const config = { apiUrl: environmentMode === "dev" ? "http://localhost:3000/v1" : "https://api.prod.com/v1", };
Pros:
Cons:
By adopting the prefix-based approach or carefully considering alternatives, you can achieve a clean, maintainable environment variable management strategy.
If you have suggestions or other approaches, feel free to share in the comments!
Best regards,
Ahmed
The above is the detailed content of Handling Environment Variables Intelligently in Vite and React Applications. For more information, please follow other related articles on the PHP Chinese website!