在当前项目中添加路由页面
# 安装router
yarn add vue-router@4
路由页面编写过程看代码
页面如下:
现在我们重新执行一下docker-compose up
打开http://localhost:4000
切换路由没有问题,当切换到/about
路由的时候,刷新页面,页面就不见了
其实道理很简单:在静态资源中并没有 about 或者 about.html 该资源,因此返回 404 Not Found。而在单页应用中,/about 是由前端通过 history API 进行控制。
解决方法也很简单:在服务端将所有页面路由均指向 index.html,而单页应用再通过 history API 控制当前路由显示哪个页面。 这也是静态资源服务器的重写(Rewrite)功能。
我们在使用 nginx 镜像部署前端应用时,可通过挂载 nginx 配置解决该问题。
nginx 的 try_files 指令
在 nginx 中,可通过 try_files 指令将所有页面导向 index.html。
location / {
# 如果资源不存在,则回退到 index.html
try_files $uri $uri/ /index.html;
}
此时,可解决服务器端路由问题。
配置Dockerfile
FROM node:14-alpine as builder
WORKDIR /code
# 单独分离 package.json,是为了安装依赖可最大限度利用缓存
ADD package.json yarn.lock /code/
RUN yarn
ADD . /code
RUN npm run build
# 选择更小体积的基础镜像
FROM nginx:alpine
# 挂载nginx配置
ADD nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder code/dist /usr/share/nginx/html
更新一下docker-compose,yaml
version: "3"
services:
simple:
build:
context: .
dockerfile: simple.Dockerfile
ports:
- 4000:80
route:
build:
context: .
dockerfile: router.Dockerfile
ports:
- 3000:80
启动docker-compose up
4000端口的页面还是会失效,3000端口已经成功了
长期缓存 (Long Term Cache)
在 CRA 应用中,./build/static 目录均由 webpack 构建产生,资源路径将会带有 hash 值。
此时可通过 expires 对它们配置一年的长期缓存,它实际上是配置了 Cache-Control: max-age=31536000 的响应头。
那为什么带有 hash 的资源可设置长期缓存呢: 资源的内容发生变更,他将会生成全新的 hash 值,即全新的资源路径。而旧有资源将不会进行访问。
location /static {
expires 1y;
}
启动routerdocker-compose up --build route
可以看到,带hash的文件已经设置了长效缓存了
非带hash的资源,不设置缓存