Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to force vite clearing cache in vue3

I have a side project with Vue.js 3 and vite as my bundler.

After each build the bundled files got the same hash from the build before, like:

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

so after each new build (with the same hash on the files) I had to reload the browser hard to clear the cache and see the changes I made.

I tried forcing a clearing with a different version number in the package.json, but:

  1. It does not work in the Vite/Rollup environment,
  2. it doesn't make sense to enter a new number by hand every time after a change.

Question:

Is there any way to configure vite to randomly create new hashes after a new build, or do you know another trick to clear the cache?

like image 203
wittgenstein Avatar asked Dec 01 '25 20:12

wittgenstein


1 Answers

I found a solution how to add a random hash with each file with the build process witch will clear the cache in the browser:

// 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;

output:

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

...
like image 85
wittgenstein Avatar answered Dec 05 '25 06:12

wittgenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!