Skip to content

Commit 2186a27

Browse files
committed
feat: add cacheAssets option to useVite for improved asset caching
1 parent 07f230e commit 2186a27

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

zerva-vite/src/module.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export function useVite(config?: {
2323
www?: string
2424
mode?: string
2525
// hmr?: boolean
26+
cacheAssets?: boolean
2627
}) {
2728
const log = LoggerFromConfig(config?.log ?? true, moduleName, LogLevelInfo)
2829
log(`use ${moduleName} ${process.env.ZERVA}`)
@@ -35,6 +36,7 @@ export function useVite(config?: {
3536
www = './dist_www',
3637
mode = (ZERVA_DEVELOPMENT ? 'development' : 'production'),
3738
// hmr = true,
39+
cacheAssets = true,
3840
} = config ?? {}
3941

4042
const rootPath = toPath(root)
@@ -95,10 +97,15 @@ export function useVite(config?: {
9597
const multiInputCache: Record<string, string> = {}
9698

9799
// Cache static assets
98-
app.get(/[^\/]assets\//, (req: any, res: any) => {
99-
res.setHeader('Cache-Control', 'max-age=31536000, immutable')
100-
// Cache-Control: max-age=31536000, immutable
101-
})
100+
if (cacheAssets) {
101+
app.use((req, res, next) => {
102+
const path = req.path
103+
if (path.includes('/assets/') || /.*\.(?:png|ico|svg|jpg|pdf|jpeg|mp4|mp3|woff2|ttf|tflite)$/.test(req.path)) {
104+
res.setHeader('Cache-Control', 'max-age=31536000, immutable')
105+
}
106+
next()
107+
})
108+
}
102109

103110
// Map dynamic routes to index.html
104111
app?.get(/.*/, (req: any, res: any) => {

0 commit comments

Comments
 (0)