vue 项目每一次打包上线,都会有浏览器缓存问题,需要用户手动清除缓存。
这样用户体验非常不好,所以我们在打包部署的时候需要尽量避免浏览器的缓存。
下面是我的解决方案:

缓存问题

方法一

index.html文件添加如下代码

<meta http-equiv="pragram" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="expires" content="0">

在这里插入图片描述

方法二

通过给打包的文件路径添加时间戳,在根目录创建vue.config.js文件,并添加如下代码:

const path = require("path");
const webpack = require("webpack");
const timeStamp = new Date().getTime();
module.exports = {
  publicPath: process.env.NODE_ENV === "production" ? "/dist/" : "/",
  // 打包的时候不使用hash值.因为我们有时间戳来确定项目的唯一性了.
  filenameHashing: false,

  // 将构建好的文件输出到哪里
  outputDir: "dist",

  configureWebpack: {
    // 重点
    // 输出重构 打包编译后的js文件名称,添加时间戳.
    output: {
      filename: `js/[name].${timeStamp}.js`,
      chunkFilename: `js/chunk.[id].${timeStamp}.js`
    }
  },

  css: {
    //重点.
    extract: {
      // 打包后css文件名称添加时间戳
      filename: `css/[name].${timeStamp}.css`,
      chunkFilename: `css/chunk.[id].${timeStamp}.css`
    }
  }
};

  • filename 指列在entry 中,打包后输出的文件的名称。
  • chunkFilename 指未列在entry 中,却又需要被打包出来的文件的名称。

方法三

nginx 配置,让index.html不缓存。

location = /index.html {
    add_header Cache-Control "no-cache, no-store";
}

部署问题

问题一

项目本地启动无问题,部署上线后访问,控制台提示 引用静态资源报错:net::ERR_ABORTED 404 (Not Found)

解决:

  • 一、可能是因为vue.config.js中的publicPath路径错误;保证自己路径正确的前提下,将publicPath修改为如下代码:
publicPath: process.env.NODE_ENV === "production" ? "/dist/" : "/",

在这里插入图片描述

  • 二、可能是因为打包后的dist没有放到服务器的根目录下,查看config文件夹下的index.js文件,找到build.assetsPublicPath,将"/“修改成”./"

在这里插入图片描述

问题二

项目打包后只能访问首页,其他页面全部报错404或者显示空白

解决:

  • 查看路由表,是否将路由模式设置为了history模式,如果设置了,只需将 history 注释掉 然后 将项目打包后上到环境就可以了
    在这里插入图片描述
Logo

前往低代码交流专区

更多推荐