【问题标题】:how to force vite clearing cache in vue3如何在vue3中强制vite清除缓存
【发布时间】:2021-09-03 20:31:39
【问题描述】:

我有一个附带项目,Vue.js 3vite 作为我的捆绑器。

在每次构建之后,捆绑的文件都会从之前的构建中获得相同的哈希值,例如:

index.432c7f2f.js   <-- the hash will be identical after each new build
index.877e2b8d.css
vendor.67f46a28.js

所以在每次新构建之后(在文件上使用相同的哈希),我不得不重新加载浏览器以清除缓存并查看我所做的更改。

我在package.json 中尝试了forcing a clearing with a different version number,但是:

  1. 在 Vite/Rollup 环境下不工作,
  2. 每次更改后都手动输入新号码是没有意义的。

问题:

有什么方法可以配置 vite 在新构建后随机创建新的哈希,或者你知道清除缓存的另一个技巧吗?

【问题讨论】:

    标签: caching bundle vuejs3 rollup vite


    【解决方案1】:

    我发现a solution如何在构建过程中为每个文件添加随机哈希,这将清除浏览器中的缓存:

    // vite.config.js
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import { hash } from './src/utils/functions.js'
    
    export default defineConfig({
      plugins: [vue()],
      build: {
        rollupOptions: {
          output: {
            entryFileNames: `[name]` + hash + `.js`,
            chunkFileNames: `[name]` + hash + `.js`,
            assetFileNames: `[name]` + hash + `.[ext]`
          }
        }
      }
    })
    
    // functions.js
    export const hash = Math.floor(Math.random() * 90000) + 10000;
    

    输出:

    dist/index.html
    dist/index87047.css
    dist/index87047.js
    dist/vendor87047.js
    
    or
    
    dist/index.html
    dist/index61047.css
    dist/index61047.js
    dist/vendor61047.js
    
    ...
    

    【讨论】:

    • 太好了。这个对我有用。我可以刷新页面并获取构建内容。但我不明白为什么。 Vite 似乎已经在其文件中添加了随机数?这有什么不同?
    • 是的,但是应该可以在不刷新页面的情况下看到新内容。随机散列将为您做到这一点。这样一来,每个用户(甚至是之前访问过您网站的用户)都会看到最新的内容。
    • 是的,我注意到了,这就是我首先尝试这样做的原因,这正是超级 gerat :D 我只是感到困惑,因为 Vite 已经为文件提供了字母数字哈希。为什么它不能立即工作,而是需要强制数字哈希?
    • 这就是问题所在。哈希没有改变。 浏览器缓存认为它是旧文件。使用随机散列,浏览器会自动获取新文件并显示所有新更改的站点。请记住,并非每个用户都会更新您的页面。这就是这个随机散列将为您做的事情。
    • 非常感谢您的解释。这很有意义。只是为了澄清一下:如果直接在 vite.config.js 中编写,哈希 var 来自导入只是一种偏好或是否重要?
    猜你喜欢
    • 2014-12-23
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-05-02
    • 2016-02-18
    相关资源
    最近更新 更多