# Vue3教程 - 23 多环境配置与发布
在实际的开发中,项目会分为生产和测试环境,针对不同的环境会有不同的配置,例如服务器地址等。
所以需要针对不同的环境使用不同的配置文件,总不能每次都修改,容易出错。
# 23.1 创建配置文件
在 Vue 3 中进行多环境配置时,通常会借助 Vite 的环境变量功能。
首先在项目根目录创建.env
文件即可。
- 创建普通全局变量
.env
- 创建开发环境变量
.env.development
- 创建测试环境变量
.env.test
- 创建生产环境变量
.env.production
在这些文件中,可以定义环境变量,格式为 VITE_
开头,格式是:VITE_变量名=值
,如:
# 在.env.development文件中
VITE_API_URL=http://localhost:8080/api
# 在.env.test文件中
VITE_API_URL=https://test.doubibiji.com/api
# 在.env.production文件中
VITE_API_URL=https://www.doubibiji.com/api
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 23.2 使用环境变量
在 Vue 组件或 JS/TS 脚本文件中,可以通过 import.meta.env
来访问这些变量。例如:
console.log(import.meta.env.VITE_API_URL);
// 创建一个 Axios 实例
const instance = axios.create({
baseURL: import.meta.env.VITE_API_URL, // 修改为你的API基础URL
timeout: 10 * 1000 // 请求超时时间
});
1
2
3
4
5
6
7
2
3
4
5
6
7
另外还有两个常用的预定义的环境变量:
import.meta.env.MODE
:为自带的默认变量,会自动设置为上边对应的模式名称,例如development
、test
、production
。import.meta.env.BASE_URL
:基础路径配置,对应vite.config.ts
中的base
配置项。前面讲路由的时候,讲解路由模式的时候有讲过。
我们可以在代码中进行环境的判断:
if (import.meta.env.MODE === 'development') {
console.log('当前是开发环境');
} else if (import.meta.env.MODE === 'production') {
console.log('当前是生产环境');
} else if (import.meta.env.MODE === 'test') {
console.log('当前是测试环境');
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 23.3 修改package.json脚本
在 package.json
文件中,你可以通过 --mode
参数指定构建或启动时使用的环境:
"scripts": {
"dev": "vite --mode development", // 以开发环境运行
"dev:test": "vite --mode test", // 以测试环境运行
"build:test": "vite build --mode test", // 以测试环境打包
"build:prod": "vite build --mode production", // 以生产环境打包
// ...其他
},
1
2
3
4
5
6
7
2
3
4
5
6
7
根据自己的需要配置运行和打包的命令。
# 23.4 运行命令
根据 package.json
中的配置运行命令(根据上面的命令来的):
- 开发环境运行:
npm run dev
- 测试环境运行:
npm run test
- 测试环境打包:
npm run build:test
- 生产环境打包:
npm run build:prod
打包后,会在项目根目录下生成一个 dist
文件夹,就可以发布到 Nginx 服务器下了。
# 23.5 发布
将打包的 dist
文件夹中的内容放到 Nginx 的站点目录下。或者修改 Nginx 配置,将站点目录设置为 dist
文件夹所在位置。
另外需要配置反向代理,解决前端的跨域问题,将 /api
开头(当然这个是自定义的)的请求转发给后端的服务器。
# nginx 配置文件
server {
listen 80;
server_name localhost;
location /api/ { // 将后端的请求转发到后端服务器
proxy_pass http://localhost:8090/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 40M;
}
location / {
root /usr/share/nginx/html/dist; // 设置为dist所在目录
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# ...其他配置
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21