First you need to know the following things:
Access environment variables in .env files via " import.meta.env.Specific variable name"
Correct way: import.meta.env.VITE_APP_TITLE
Incorrect way: import.meta.env[key]
The environment variables in the .env file must be prefixed with VITE_ , otherwise they cannot be referenced successfully.
Correct way: VITE_APP_TITLE = 'vite'
Incorrect way: TE_WORD = 123
Different file types starting with .env load different environment variables, such as:
.env is loaded in all cases
.env,local is loaded in all cases, but ignored by git
.env.[mode] is only loaded in the corresponding mode
.env.[mode].local is only loaded in the corresponding mode, but is ignored by git
To obtain different environment variable values according to different modes during the packaging process, you need to use the --mode option flag to override the default mode used by the command. For example, development environment/test environment/production environment all correspond to different titles:
First create three .env files in the project root directory corresponding to three environment variables.
.env.development 下:
# 开发环境配置
VITE_APP_TITLE = '开发标题'
Under .env.test:
# 测试环境配置
VITE_APP_TITLE = '测试标题'
Under .env.staging:
# 生产环境配置
VITE_APP_TITLE = '生产标题'
Pass the --mode option flag in the scripts in the package.json file to override the default mode used by the command
{
"scripts": {
"dev": "vite",
"build:prod": "vite build",
"build:stage": "vite build --mode staging", //对应生产标题
"build:test": "vite build --mode test", //对应测试标题
"build:dev": "vite build --mode development", //对应开发标题
"preview": "vite preview"
},
}
use:
const uploadFileUrl = ref(import.meta.env.VITE_APP_TITLE)
Attached is an introduction to vite’s official website for your reference.