Configuring Environments and Getting Current Environment in Vite Projects
4/19/23Less than 1 minute
Reference: https://vitejs.dev/guide/env-and-mode.html#env-variables
Introduction
In a project, you can configure different variables for production and development environments. This allows you to directly run build commands without modifying files when packaging.
Steps
- Create three new files
.env.local,.env.production, and.env.developmentin the root directory of the project.
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.production # loaded in production environment
.env.development # loaded in development environment
- Add configuration to the files.
VITE_HTTP_BASE_URL=http://localhost:3600/Note: To prevent accidentally leaking environmental variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.
- You can get the configured values in your project using
import.meta.env.
console.log(import.meta.env);
- You will be happy to see some built-in variables that are available in all cases:
import.meta.env.MODE: {string} The mode the app is running in.import.meta.env.BASE_URL: {string} The base URL the app is being served from. This is determined by thebaseconfig option.import.meta.env.PROD: {boolean} Whether the app is running in production.import.meta.env.DEV: {boolean} Whether the app is running in development (always the opposite ofimport.meta.env.PROD).import.meta.env.SSR: {boolean} Whether the app is running on the server.
AI Translation | AI 翻译
This article was translated from Chinese to English by AI. If there are any inaccuracies, please refer to the original Chinese version.
本文由 AI 辅助从中文翻译为英文。如遇不准确之处,请以中文原版为准。
