jtwang7 / React-Note

React 学习笔记
8 stars 2 forks source link

React 项目打包之 homepage #25

Open jtwang7 opened 3 years ago

jtwang7 commented 3 years ago

React 项目打包之 homepage

前言

在项目部署过程中,碰到如下问题: 当访问路径与 /mobile/ 匹配时,nginx 找到 /root/web-mobile/build/ 路径下的 index.html 文件并返回。其中 nginx.conf 配置文件关键部分如下:

server {
    ......

    location / {
            root    /root/picture-wall/build/;
            index   index.html index.htm;
    }

    location ^~ /mobile/ {
            alias   /root/web-mobile/build/;
            index   index.html index.htm;
    }

    ......

上述配置没有错误,最终返回给前端的实际上是 /root/web-mobile/build/index.html 文件。 但是! 用浏览器访问时发现返回了空白页面,查找控制台报错原因,发现❌错误竟然是没有访问到 css 文件。

解决

在 react 项目打包时,运行 npm run build,我们会在控制台看到下面这段话:

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

它告诉我们项目是以 / 为项目的假设部署路径进行打包的,也就是说,打包出来的项目文件,其都是基于 / 进行加载的。 而我们实际访问 index.html 页面时,css 的加载路径位于 /mobile/ 下,很显然从该路径下浏览器是没有办法找到 css 文件的。 因此,在项目 build 时,我们要保证项目的假设部署路径与实际访问路径一致,通过修改 package.json 中的 homepage 配置项实现:

// package.json
{
  "name": "web-mobile",
  "version": "0.1.0",
  "private": true,
  "homepage": "/mobile", // 修改项目部署路径
  "dependencies": {
      ....
   }
   ...
}