How to add process.env when using vite?

by tressie.damore , in category: Javascript , 2 months ago

How to add process.env when using vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 2 months ago

@tressie.damore 

To add process.env variables in Vite, you need to create a .env file at the root of your project and define your environment variables inside it. The variables should be in the format VITE_MY_VARIABLE=value.


For example, if you want to define a variable called API_URL, you would add the following line to your .env file:

1
VITE_API_URL=https://api.example.com


Then, you can access this variable in your code by using import.meta.env.VITE_API_URL.


Make sure to restart your Vite server after adding or updating environment variables in the .env file.


Additionally, if you want to use different variables for different environments (e.g., development, production), you can create separate .env files (e.g., .env.development, .env.production) and Vite will automatically load the appropriate file based on the current environment.