在当前项目中添加路由页面

  1. # 安装router
  2. yarn add vue-router@4

路由页面编写过程看代码
页面如下:
image.png
现在我们重新执行一下docker-compose up
打开http://localhost:4000切换路由没有问题,当切换到/about路由的时候,刷新页面,页面就不见了
image.png
其实道理很简单:在静态资源中并没有 about 或者 about.html 该资源,因此返回 404 Not Found。而在单页应用中,/about 是由前端通过 history API 进行控制。
解决方法也很简单:在服务端将所有页面路由均指向 index.html,而单页应用再通过 history API 控制当前路由显示哪个页面。 这也是静态资源服务器的重写(Rewrite)功能。
我们在使用 nginx 镜像部署前端应用时,可通过挂载 nginx 配置解决该问题。

nginx 的 try_files 指令

在 nginx 中,可通过 try_files 指令将所有页面导向 index.html。

  1. location / {
  2. # 如果资源不存在,则回退到 index.html
  3. try_files $uri $uri/ /index.html;
  4. }

此时,可解决服务器端路由问题。

配置Dockerfile

  1. FROM node:14-alpine as builder
  2. WORKDIR /code
  3. # 单独分离 package.json,是为了安装依赖可最大限度利用缓存
  4. ADD package.json yarn.lock /code/
  5. RUN yarn
  6. ADD . /code
  7. RUN npm run build
  8. # 选择更小体积的基础镜像
  9. FROM nginx:alpine
  10. # 挂载nginx配置
  11. ADD nginx.conf /etc/nginx/conf.d/default.conf
  12. COPY --from=builder code/dist /usr/share/nginx/html

更新一下docker-compose,yaml

  1. version: "3"
  2. services:
  3. simple:
  4. build:
  5. context: .
  6. dockerfile: simple.Dockerfile
  7. ports:
  8. - 4000:80
  9. route:
  10. build:
  11. context: .
  12. dockerfile: router.Dockerfile
  13. ports:
  14. - 3000:80

启动docker-compose up
4000端口的页面还是会失效,3000端口已经成功了

长期缓存 (Long Term Cache)

在 CRA 应用中,./build/static 目录均由 webpack 构建产生,资源路径将会带有 hash 值。
此时可通过 expires 对它们配置一年的长期缓存,它实际上是配置了 Cache-Control: max-age=31536000 的响应头。
那为什么带有 hash 的资源可设置长期缓存呢: 资源的内容发生变更,他将会生成全新的 hash 值,即全新的资源路径。而旧有资源将不会进行访问。

  1. location /static {
  2. expires 1y;
  3. }

启动router
docker-compose up --build route
可以看到,带hash的文件已经设置了长效缓存了
image.png
非带hash的资源,不设置缓存
image.png