问题答案 12026年5月29日 06:23
How can I get Vite env variables?
Define Environment Variables:In the project root directory, create a file to define your environment variables. Vite requires environment variables to start with . For example, create a file and add the following content:Here, two environment variables are defined: and .Access Environment Variables:In your Vite project code, use to access the defined environment variables. For example:This code retrieves the values of the and environment variables defined in the file earlier.Modes and Environment Variable Files:For different environments (such as development and production), prepare different files. For example, and . When you run or build the project, Vite automatically loads the corresponding file based on the current mode.Type Declaration (Optional):To get better type hints in TypeScript projects, declare the types of environment variables in the file:This allows TypeScript to know which environment variables are available and provides the correct types for them.For example, suppose we are developing a frontend application that needs to call an API. We might need a base URL for the API and an API key. In development and production environments, these values are typically different. We can set up the environment variables as follows:In the file:In the file:When running or building the application in different environments, Vite automatically loads the correct environment variable file, and your code can seamlessly use these variables to make API calls.