完整的标题:路由前缀,vue.config.js中的publicPath配置和nginx的location、alias、root之间的关系
1. 路由前缀
vue-router v4 设置路由前缀
在进行路由跳转时,都加上设定的固定前缀
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory('前缀'),
routes: [
//...
],
})
vue-router v3 设置路由前缀
const router = new Router({
mode: 'history',
base: '前缀',
})
vue2 用的是vue-router v3版本,vue3用的是vue-router v4版本
2. vue.config.js中的publicPath
publicPath用来设置文件访问路径的前缀,即:项目中的所有静态资源的访问路径都会加上这个设定的前缀
module.exports = defineConfig({
publicPath: '/vue3',
})
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="/vue3/favicon.ico">
<title>vue3_test</title>
<!-- **在引入资源时,加上了 指定的前缀** -->
<script defer src="/vue3/js/chunk-vendors.js"></script>
<script defer src="/vue3/js/app.js"></script></head>
<body>
<noscript>
<strong>We're sorry but vue3_test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
Tip: 在vue.config.js中配置了publicPath后,项目中的所有静态资源的访问路径都会加上这个设定的前缀,不仅仅是在dist/index.html引入资源时
3. publicPath和路由前缀的关系
路由前缀设置成 /mgt publicPath设置成/vue3
浏览器输入:http://localhost:8080/mgt/about
本地环境下 url和资源请求的地址并不一致 项目依旧可以正常使用(原因并未深入研究),打包部署到服务器后,就无法访问项目了
下面是打包部署后的效果
总结:publicPath和路由前缀是两个不同的东西,要打包后的项目能正常运行,publicPath和路由前缀要设置成一致
4. 项目部署到非根目录下时,路由前缀,publicPath字段 和nginx的location、alias、root、文件夹名之间的关系
注意:第4点的前提是,前端项目需要部署到非根目录下,比如:/pc /h5
①:路由前缀,publicPath字段一般设置成一样的,所以用 ①来表示 ②:location ③:alias ④:root ⑤:文件夹名
如果①和⑤不一致,会导致index.html可以访问,但是index.html中引入的css、js等资源无法访问,因为publicPath指定了资源引入路径
不管root还是alias指定路径都是这个情况
root和location、文件夹名的组合
用root来指定目录,location和文件夹名是一定一致的不然找不到文件
所以,用root来指定路径要求① ② ⑤ 名称要一致
server {
listen 80 ;
server_name localhost;
# 一、用root来指定目录
# 用root来指定目录,location和文件夹名要一致,①也是一致的
# http://localhost/mgt/ 可以正常使用
location /mgt {
root G:/TestProject;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
alias和location、文件夹名的组合
location和alias名称可以不一致,当项目部署在非根目录下时,如果location和publicPath不一致时,会导致index.html可以访问,但是index.html中引入的css、js等资源无法访问
alias配置路径时,location 和 文件夹名可以不一致
# 路由前缀和publicPath设置的值为,/mgt
# 这个规则可以正常访问项目
location /mgt {
alias G:/TestProject/mgtDX;
index index.html index.htm;
}
所以,用alias来指定路径要求① ② 名称要一致
location /mgt {
alias G:/TestProject/mgt;
index index.html index.htm;
}
总结
将前端项目部署到非根目录下,用root配置路径时:路由前缀、publicPath、location、文件夹名 要保持一致,用alias配置路径时:路由前缀、publicPath、location 要保持一致
5. 项目部署到根目录下
location / {
root G:/TestProject/dist;
index index.html index.htm;
}
location / {
alias G:/TestProject/dist/; # 末尾记得加 / 否则会找不到文件
index index.html index.htm;
}
部署到根目录下,路由前缀、publicPath不需要手动去指定,因为其默认值就是 /, alias或root配置成 / 即可,文件夹名随便叫啥