webpack/vite打包中publicPath(base) router.base axios.baseURL参数作用

1. publicPath配置(vite中是base属性):

publicPath配置build打包的资源存放公共路径,当我们打包的时候webpack会在静态文件路径前面添加publicPath的值,一般和router里base属性结合使用(加载时会此publicPath目录中寻找资源)。当我们把资源放到CDN上的时候,把publicPath的值设为cdn地址

比如配置了publicPath: /project/hx.con

在index.html入口文件中打包后的chunk.js、chunk.css等资源都会加前缀路径(/project/hx.con/chunk.js)

然后我们需要将打包后资源放到【nginx root指定的根目录】/project/hx.con下:mv ./dist /lbsmart.public/project/hx.con

2.nginx root/alias location定位资源

root、alias都是用来指定url根路径(/)代表的资源目录的

使用root:当你想为整个服务器或者特定位置提供一个统一的根目录时,使用root是最简单直接的方法。

使用alias:当你需要对服务器上的特定资源进行映射,而这部分资源又不在当前的根目录中时,alias是不可或缺的(alias会把location后面配置的路径丢弃掉)

比如如下nginx配置:

       index index.html; # 网站初始页(即直接localhost:端口 访问的页面)

       root  /lbsmart.public; #根目录

        location / { index  index.html; }

访问http://localhost/project/hx.con时:

即从/lbsmart.public/project/hx.con/index.html 这个路径加载index.html资源文件并返回。

额外: 重写  &  重定向

利用URL重写,我们可以很方便地实现长短地址的转换,但是用重定向就不合适了。

rewrite ^grab /public/files/download/download.php  ( rewrite {规则} {定向路径} {重写类型})

若访问http://mysite/grab?file=my.zip

则会执行该页面:

http://mysite/public/files/download/download.php?file=my.zip

若是重定向规则:(浏览器端重新发请求)

若访问http://mysite/grab?file=my.zip

则会执行该页面:

http://mysite/public/files/download/download.php

3.router配置 base(保证路由能识别publicPath前缀)

对于history模式,假设项目的publicPath为/project/hx.con。

3-1.由于router中路由的path一般是/about这样。 为了让router可以识别到localhost/project/hx.con/about,需要配置router的参数: base: /project/hx.con

3-2.访问http://localhost/project/hx.con/about的时候,服务器会去找/project/hx.con指向的打包资源目录下的about子目录或文件,很显然因为是单页面应用,并不会存在about这个目录或者文件,就会导致404错误:

我们要配置nginx让这种情况下,服务器能够返回单页应用的index.html,然后剩下的路由解析的事情就交给前端vue-router来完成即可。

            root  /lbsmart.public;

        location / {

          try_files $uri $uri/ @router;

          index  index.html;

        }

        location @router {

          rewrite ^.*$ /index.html last;

        }

这句配置的意思就是,拿到一个地址,先根据地址尝试找对应文件,找不到再试探地址对应的文件夹,再找不到就返回rewrite /index.html的结果(即/lbsmart.public/project/hx.con/index.html文件)。再次打开刚才的about地址,刷新页面也不会404啦.

4.axios配置baseURL

为了避免后端接口端口和前端不同导致cors跨域,一般会设置一个接口的公共前缀baseURL,这样axios发出的所有接口都会增加这个前缀url。

比如: baseURL: /prod-api

然后nginx中可以配置location转发以/prod-api开头的url给后端服务处理。

       location /prod-api/ { #后端接口转发

                proxy_pass http://10.100.2.74:9151;   #后端接口地址

                proxy_cookie_path / /prod-api;

                rewrite ^/prod-api/(.*) /$1 break;

                client_max_body_size 500m;

        }

PS:完整nginx.conf参数配置见`ubuntu22部署 vue 和 springboot项目_ubuntu nodejs+vue + element-plus + springboot环境搭建-CSDN博客`部分:

  • 25
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李庆政370

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值