Managing Environment-Specific Logging and Configuration in a Vite React Application
- How to show console logs according to the environment.
- How to load environment variables in your application.
- How to load the correct environment file (with Vite or Yarn).
- How to start the application with the production build.
1. Show Console Logs According to the Environment
To ensure that console.log, console.warn, and console.error only work in specific environments (e.g., test mode), you can create a utility module that conditionally logs based on the environment.
Example: logUtil.ts
const isTestEnv = import.meta.env.VITE_ENV === 'test';
const logUtil = {
log: <T>(...args: T[]) => {
if (isTestEnv) {
console.log(...args);
}
},
warn: <T>(...args: T[]) => {
if (isTestEnv) {
console.warn(...args);
}
},
error: <T>(...args: T[]) => {
if (isTestEnv) {
console.error(...args);
}
},
};
export default logUtil;
Explanation:
- Environment Check: The
isTestEnvvariable checks if theVITE_ENVenvironment variable is set to"test". - Conditional Logging: The
logUtilmethods (log,warn,error) only executeconsolestatements if the environment istest. - Type Safety: The utility uses TypeScript generics (
<T>) to ensure type safety for the logged arguments.
Usage:
import logUtil from './utils/logUtil';
logUtil.log("This will only log in test mode");
logUtil.warn("This warning will only appear in test mode");
logUtil.error("This error will only appear in test mode");
2. Load Environment Variables in Your Application
Vite automatically exposes environment variables prefixed with VITE_ to your application via import.meta.env. To use environment-specific variables:
Example: .env.test
VITE_ENV=test
VITE_API_URL=https://api.test.example.com
Accessing Environment Variables:
const apiUrl = import.meta.env.VITE_API_URL;
console.log(apiUrl); // Outputs: https://api.test.example.com
Rules:
- Prefix all environment variables with
VITE_(e.g.,VITE_ENV,VITE_API_URL). - Access them in your application using
import.meta.env.
3. Load the Correct Environment File (with Vite or Yarn)
Vite loads environment variables from .env files based on the mode specified during the build or development process.
Environment Files:
.env: Default environment file (loaded in all modes)..env.test: Loaded when the mode istest..env.production: Loaded when the mode isproduction.
Specifying the Mode:
- During Development:
yarn dev --mode test
- During Build:
yarn build --mode test
Example Workflow:
-
Create a
.env.testfile:VITE_ENV=testVITE_API_URL=https://api.test.example.com -
Build the application in test mode:
yarn build --mode test -
Vite will load the
.env.testfile and expose its variables viaimport.meta.env.
4. Start the Application with the Build
After building your application, you need to serve the production files. Use a static server like serve or Vite's built-in preview command.
Option 1: Using serve
-
Install
serveglobally or locally:yarn global add serveOr:
yarn add serve -
Serve the production build:
serve -s dist- The
-sflag ensures all routes fall back toindex.html(useful for SPAs). - The
distdirectory is the default output directory for Vite builds.
- The
-
Access the application at
http://localhost:3000.
Option 2: Using Vite's Preview Command
-
Add a
previewscript to yourpackage.json:"scripts": {"build": "vite build","preview": "vite preview"} -
Build the application:
yarn build --mode test -
Start the preview server:
yarn preview- This serves the production build at
http://localhost:4173(or another port if specified).
- This serves the production build at
Summary
-
Environment-Specific Logging:
- Use a utility like
logUtil.tsto conditionally log based on the environment.
- Use a utility like
-
Loading Environment Variables:
- Prefix variables with
VITE_and access them viaimport.meta.env.
- Prefix variables with
-
Loading the Correct Environment File:
- Use the
--modeflag withyarn devoryarn buildto load the appropriate.envfile.
- Use the
-
Starting the Application with the Build:
- Serve the production build using
serveor Vite'spreviewcommand.
- Serve the production build using