Version static asset URLs by a fingerprint of the files, so browsers fetch new scripts after each deploy

This commit is contained in:
zyphlar
2026-11-07 23:26:45 -08:00
parent 1db425d493
commit f08207516d
2 changed files with 77 additions and 4 deletions
+42
View File
@@ -0,0 +1,42 @@
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ASSET_VERSION, staticFingerprint } from '../src/version'
let dir: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'imp-assets-'))
mkdirSync(join(dir, 'js'))
writeFileSync(join(dir, 'js', 'app.js'), 'one')
writeFileSync(join(dir, 'style.css'), 'body {}')
})
afterEach(() => rmSync(dir, { recursive: true, force: true }))
describe('static asset version', () => {
it('stays the same while the files do', () => {
expect(staticFingerprint([dir])).toBe(staticFingerprint([dir]))
expect(staticFingerprint([dir])).toMatch(/^[0-9a-f]{10}$/)
})
it('changes when a file changes, is added, or is renamed', () => {
const before = staticFingerprint([dir])
writeFileSync(join(dir, 'js', 'app.js'), 'two')
const edited = staticFingerprint([dir])
expect(edited).not.toBe(before)
writeFileSync(join(dir, 'js', 'new.js'), '')
const added = staticFingerprint([dir])
expect(added).not.toBe(edited)
rmSync(join(dir, 'js', 'new.js'))
writeFileSync(join(dir, 'js', 'renamed.js'), '')
expect(staticFingerprint([dir])).not.toBe(added)
})
it('ignores a missing folder', () => {
expect(staticFingerprint([dir, join(dir, 'nope')])).toBe(staticFingerprint([dir]))
})
it('puts the fingerprint after the package version in the asset path', () => {
expect(decodeURIComponent(ASSET_VERSION)).toMatch(/^.+-[0-9a-f]{10}$/)
})
})