项目背景
我们在开发项目需求的时候,往往会遇到多端部署的情况,比如面向用户的C端(PC),面向用户的H5(移动端),另外还有管理后台这样的情况。但是服务器资源有限,运维就给开了一个端口,前端就需要通过后缀用
ngixn
代理去区分不同的项目
项目结构
现在以C端(H5)和管理端两个项目为例,C端用的是cli vue2
为基础搭建的脚手架项目,管理端是以vite + vue3
搭建的脚手架项目
遇到的坑
第一个坑(本地开发环境正常)
1、C端H5正常打包部署都没有问题,管理端本地开发没有问题,打包后,出现语法报错
第二个坑(本地开发环境正常)
1、进入管理端页面,出404
2、输入地址进入,正常访问系统,刷新页面还会出现404
解决方案
意外的惊喜,总是会在你要在下班的时候,姗姗来迟,会迟到,但是绝不会缺席。遇到问题不慌,一个坑一个坑蹚,一个一个解决,咱们先看第一个语法报错的问题。
一般这种语法报错在
cli
里,多是publicPath
的设置原因,一般vue.congfig.js
的publicPath
改成'./'
会解决大多数的问题
相对于vite+vue3
也是同理,在vite.config.js
里把base
根据环境变量改成服务器上跟nginx
代理对应,默认情况下,vite 会假设应用是被部署在一个域名的根路径上,例如 https://www.example.com/
。如果应用被部署在一个子路径上,就需要用这个选项指定这个子路径。例如,如果应用被部署在 https://www.example.com/admin/
,则设置 base
为 /admin/
// vite.config.js
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
return {
...
// 部署生产环境和开发环境下的URL
base: env === 'production' ? '/admin' : '/',
...
}
})
对应服务器的nginx
配置
server {
listen ****;
server_name _;
location /h5/ {
alias /data/web/h5/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /admin/ {
alias /data/web/admin/dist;
index index.html index.htm;
try_files $uri $uri/ /admin/index.html;
}
location /back/ {
proxy_pass http://***.***.***.***:****/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
第二个坑,页面刷新404
,在Vue
的history
模式下,实例化router
的时候需要加上对应的路径
// https://router.vuejs.org/zh/api/
createWebHistory() // 没有 base,应用托管在域名 `https://www.example.com` 的根目录下。
createWebHistory('/admin/') // 给出的网址为 `https://www.example.com/admin/`
即在我们对应的router/index.js
实例化router
时,对应开发环境,实例化router
时设置不同的base
参数
const env = import.meta.env.VITE_APP_ENV
const router = createRouter({
history: createWebHistory(env === 'production' ? '/admin' : '/'),
routes: constantRoutes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
},
});
export default router;
总结
本地开发环境和环境部署差别很大,需要根据具体情况具体分析,不能一概而论,多沉淀多读官方文档,沉淀下来不要浮躁,能解决99%的问题