Skip to content

Commit

Permalink
fix: avif format (#708)
Browse files Browse the repository at this point in the history
Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
  • Loading branch information
AdamMerrifield and benmccann committed Mar 31, 2024
1 parent 37857f4 commit 29b3fed
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/long-baboons-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vite-imagetools': patch
---

fix: correctly set avif format when file is read from cache
35 changes: 35 additions & 0 deletions packages/vite/src/__tests__/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,41 @@ describe('vite-imagetools', () => {
expect(image).toBeTypeOf('string')
})
})

describe('cache.avifFormat', () => {
test('is avif format', async () => {
const dir = './node_modules/.cache/imagetools_test_cache_dir'
await build({
root: join(__dirname, '__fixtures__'),
logLevel: 'warn',
build: { write: false },
plugins: [
testEntry(`
import Image from "./pexels-allec-gomes-5195763.png?format=avif"
window.__IMAGE__ = Image
`),
imagetools({ cache: { dir } })
]
})

const bundle = (await build({
root: join(__dirname, '__fixtures__'),
logLevel: 'warn',
build: { write: false },
plugins: [
testEntry(`
import Image from "./pexels-allec-gomes-5195763.png?format=avif"
window.__IMAGE__ = Image
`),
imagetools({ cache: { dir } })
]
})) as RollupOutput | RollupOutput[]

const files = getFiles(bundle, '**.avif') as OutputAsset[]

expect(files).toHaveLength(1)
})
})
})

test('relative import', async () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ export function imagetools(userOptions: Partial<VitePluginOptions> = {}): Plugin

if (cacheOptions.enabled && (statSync(`${cacheOptions.dir}/${id}`, { throwIfNoEntry: false })?.size ?? 0) > 0) {
metadata = (await sharp(`${cacheOptions.dir}/${id}`).metadata()) as ImageMetadata
// we set the format on the metadata during transformation using the format directive
// when restoring from the cache, we use sharp to read it from the image and that results in a different value for avif images
// see https://github.com/lovell/sharp/issues/2504 and https://github.com/lovell/sharp/issues/3746
if (config.format === 'avif' && metadata.format === 'heif' && metadata.compression === 'av1')
metadata.format = 'avif'
} else {
const { transforms } = generateTransforms(config, transformFactories, srcURL.searchParams, logger)
const res = await applyTransforms(transforms, img, pluginOptions.removeMetadata)
Expand Down

0 comments on commit 29b3fed

Please sign in to comment.