Skip to content

Commit

Permalink
Improve next/image warnings to avoid printing more than once (#34562)
Browse files Browse the repository at this point in the history
Currently, we print warnings during `next dev` for every render of `next/image`, which can quickly fill the console making it really unfriendly to developers trying to read the logs.

This PR changes the behavior so that each unique warning prints at most once.

- Related to #33007 
- Related to #31340
  • Loading branch information
styfle committed Feb 18, 2022
1 parent 2c80444 commit a4f5463
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 9 deletions.
29 changes: 20 additions & 9 deletions packages/next/client/image.tsx
Expand Up @@ -23,6 +23,17 @@ if (typeof window === 'undefined') {
;(global as any).__NEXT_IMAGE_IMPORTED = true
}

let warnOnce = (_: string) => {}
if (process.env.NODE_ENV !== 'production') {
const warnings = new Set<string>()
warnOnce = (msg: string) => {
if (!warnings.has(msg)) {
console.warn(msg)
}
warnings.add(msg)
}
}

const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number]
type ImageConfig = ImageConfigComplete & { allSizes: number[] }
Expand Down Expand Up @@ -274,7 +285,7 @@ function handleLoading(
if (!parent.position) {
// The parent has not been rendered to the dom yet and therefore it has no position. Skip the warnings for such cases.
} else if (layout === 'responsive' && parent.display === 'flex') {
console.warn(
warnOnce(
`Image with src "${src}" may not render properly as a child of a flex container. Consider wrapping the image with a div to configure the width.`
)
} else if (
Expand All @@ -283,7 +294,7 @@ function handleLoading(
parent.position !== 'fixed' &&
parent.position !== 'absolute'
) {
console.warn(
warnOnce(
`Image with src "${src}" may not render properly with a parent using position:"${parent.position}". Consider changing the parent style to position:"relative" with a width and height.`
)
}
Expand Down Expand Up @@ -410,7 +421,7 @@ export default function Image({
)
}
if (layout === 'fill' && (width || height)) {
console.warn(
warnOnce(
`Image with src "${src}" and "layout='fill'" has unused properties assigned. Please remove "width" and "height".`
)
}
Expand All @@ -427,13 +438,13 @@ export default function Image({
)
}
if (sizes && layout !== 'fill' && layout !== 'responsive') {
console.warn(
warnOnce(
`Image with src "${src}" has "sizes" property but it will be ignored. Only use "sizes" with "layout='fill'" or "layout='responsive'".`
)
}
if (placeholder === 'blur') {
if (layout !== 'fill' && (widthInt || 0) * (heightInt || 0) < 1600) {
console.warn(
warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
)
}
Expand All @@ -453,12 +464,12 @@ export default function Image({
}
}
if ('ref' in rest) {
console.warn(
warnOnce(
`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
)
}
if ('style' in rest) {
console.warn(
warnOnce(
`Image with src "${src}" is using unsupported "style" property. Please use the "className" property instead.`
)
}
Expand All @@ -475,7 +486,7 @@ export default function Image({
url = new URL(urlStr)
} catch (err) {}
if (urlStr === src || (url && url.pathname === src && !url.search)) {
console.warn(
warnOnce(
`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
)
Expand All @@ -500,7 +511,7 @@ export default function Image({
!lcpImage.src.startsWith('blob:')
) {
// https://web.dev/lcp/#measure-lcp-in-javascript
console.warn(
warnOnce(
`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` +
`\nRead more: https://nextjs.org/docs/api-reference/next/image#priority`
)
Expand Down
23 changes: 23 additions & 0 deletions test/integration/image-component/default/pages/warning-once.js
@@ -0,0 +1,23 @@
import React from 'react'
import Image from 'next/image'

const Page = () => {
const [count, setCount] = React.useState(0)
return (
<>
<h1>Warning should print at most once</h1>
<Image
id="w"
layout="fixed"
src="/test.png"
width="400"
height="400"
sizes="50vw"
/>
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<footer>footer here</footer>
</>
)
}

export default Page
30 changes: 30 additions & 0 deletions test/integration/image-component/default/test/index.test.js
Expand Up @@ -812,6 +812,36 @@ function runTests(mode) {
await browser.elementById('without-loader').getAttribute('srcset')
).toBe('/test.svg 1x, /test.svg 2x')
})

it('should warn at most once even after state change', async () => {
const browser = await webdriver(appPort, '/warning-once')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
await browser.eval(`document.querySelector("button").click()`)
await browser.eval(`document.querySelector("button").click()`)
const count = await browser.eval(
`document.querySelector("button").textContent`
)
expect(count).toBe('Count: 2')
await check(async () => {
const result = await browser.eval(
'document.getElementById("w").naturalWidth'
)
if (result < 1) {
throw new Error('Image not loaded')
}
return 'done'
}, 'done')
const warnings = (await browser.log('browser'))
.map((log) => log.message)
.filter((log) => log.startsWith('Image with src'))
expect(warnings[0]).toMatch(
'Image with src "/test.png" has "sizes" property but it will be ignored.'
)
expect(warnings[1]).toMatch(
'Image with src "/test.png" was detected as the Largest Contentful Paint (LCP).'
)
expect(warnings.length).toBe(2)
})
} else {
//server-only tests
it('should not create an image folder in server/chunks', async () => {
Expand Down

0 comments on commit a4f5463

Please sign in to comment.