这几天为了部署前端项目的事情,头都搞大了。又没有运维的支持,全靠我这个前端开发弄,真是踩了部署的各种坑了。
这里说一下 nginx 次级域名部署基于 dvajs 开发 react 框架的静态项目的注意要点。
基于 dvajs 框架的开发环境搭建,这里我就不细说了。
编译打包
首先我们来看看项目编译后 index.html 中脚本的引入
<link href="/index.css" rel="stylesheet"></head>
<body>
<div id="root"></div>
<script type="text/javascript" src="/index.js"></script>
</body>
复制代码
不难发现引入的脚本路径是绝对的,这就有点可怕了呀!直接可能导致线上部署出问题呀!
nginx 配置
server {
listen 80;
server_name www.abc.com;
root /项目/root地址/不带sub;
location ^~ /merchantStatic/ {
root /home/projectName/src;
index index.html;
}
}
复制代码
这里服务器的配置直接导致我们访问时的地址是 www.abc.com/merchantStatic/index.html
问题描述
根据上面项目代码编译打包后生成的 index.html 文件代码和 nginx 服务器的配置,现在不难发现问题所在 - index.html 里面引入的脚本不能正常引入了。因为对应的脚本引入地址变成了 www.abc.com/index.css 和 www.abc.com/index.js,而正确的地址应该为 www.abc.com/merchantStatic/index.css 和 www.abc.com/merchantStatic/index.js,是不是?是不是?
解决问题
既然问题已经出现,而且我们已经知道问题所在,解决问题的方案那就好说了。修改 .webpackrc 里面的 publicPath 配置属性为 /merchantStatic/ 前缀目录。
修改完后重新 build 发现 index.html 里面
<link href="/merchantStatic/index.css" rel="stylesheet"></head>
<body>
<div id="root"></div>
<script type="text/javascript" src="/merchantStatic/index.js"></script>
</body>
复制代码
是我们期望的 url 。重新部署代码访问 www.abc.com/merchantStatic/index.html 没毛病了,页面很丝滑!!