在根目录新建三个文件:
- .env.test
# 测试环境
ENV = 'test'
#测试环境,Url地址
VITE_APP_BASE_URL = 'http://localhost:8080'
- .env.development
# 开发环境
ENV = 'development'
# 开发环境,Url地址
VITE_APP_BASE_URL = 'http://jdkfnbkjn.com'
- .env.production
# 生产环境
ENV = 'production'
# 生产环境,Url地址
VITE_APP_BASE_URL = 'http://djfbvkjhdsjndv.com'
使用vue cli创建的vue项目获取环境变量的方式如下
process.env.变量名
使用vite+vue3项目获取环境变量的方式如下 而且必须要以”VITE_“开头的变量才能被识别读取。
import.meta.env.变量名
package.json
{
"name": "vue3-demo",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --mode development",
"dev:test": "vite --mode test",
"build": "vue-tsc && vite build --mode production",
"preview": "vite preview"
},
"dependencies": {
"element-plus": "^2.2.25",
"pinia": "^2.0.27",
"vue": "^3.2.41",
"vue-router": "4"
},
"devDependencies": {
"@vitejs/plugin-vue": "^3.2.0",
"typescript": "^4.6.4",
"unplugin-auto-import": "^0.12.0",
"unplugin-vue-components": "^0.22.11",
"vite": "^3.2.3",
"vue-tsc": "^1.0.9"
}
}