wit*_*ein 15 caching bundle rollup vuejs3 vite
我有一个副业项目,Vue.js 3并vite作为我的捆绑商。
每次构建之后,捆绑的文件都会从之前的构建中获得相同的哈希值,例如:
index.432c7f2f.js <-- the hash will be identical after each new build
index.877e2b8d.css
vendor.67f46a28.js
Run Code Online (Sandbox Code Playgroud)
因此,在每次新构建之后(文件上具有相同的哈希值),我必须重新加载浏览器以清除缓存并查看我所做的更改。
我尝试在 中使用不同的版本号强制清除package.json,但是:
有没有办法配置 vite 在新构建后随机创建新哈希,或者您知道清除缓存的另一个技巧吗?
wit*_*ein 23
我找到了一个解决方案 ,如何使用构建过程为每个文件添加随机哈希,这将清除浏览器中的缓存:
// 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]`
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
// functions.js
export const hash = Math.floor(Math.random() * 90000) + 10000;
Run Code Online (Sandbox Code Playgroud)
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
...
Run Code Online (Sandbox Code Playgroud)
要摆脱 @wittgenstein 的回答,您也可以使用以下版本package.json(当您需要确保在发布到生产环境时缓存已被破坏时):
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { version } from './package.json'
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
output: {
entryFileNames: `[name].js?v=${version}`,
chunkFileNames: `[name].js?v=${version}`,
assetFileNames: `[name].[ext]?v=${version}`
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
它不一定是文件名本身,浏览器将看到作为不同文件添加到文件中的任何查询参数
PWA 可能会出现这样做的问题,因为只需将版本添加到文件名中,类似于上面的解决方案:
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { version } from './package.json'
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
output: {
entryFileNames: `[name].${version}.js`,
chunkFileNames: `[name].${version}.js`,
assetFileNames: `[name].${version}.[ext]`
}
}
}
})
Run Code Online (Sandbox Code Playgroud)