Unverified Commit cdb0c474 authored by Steven's avatar Steven Committed by GitHub

Improve `next/image` error message when `src` prop is missing (#38847)

Currently, when a user forgets the `src` prop on an image, an error is thrown. However that error doesn't include any of the the user's code in the stack trace, so its nearly impossible to figure out which image is the culprit if there are multiple images on the page.

Since this error only throws on demand when a page is visited during `next dev`, we can instead delay the error so it no longer prints on the server but prints on mount instead. At that point, we'll have the `<img>` element via ref and can print it to the web console with the stack trace.

- Fixes #23742 
parent 672bdaee
...@@ -357,10 +357,6 @@ export default function Image({ ...@@ -357,10 +357,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:') || src.startsWith('blob:')) { if (src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -373,15 +369,17 @@ export default function Image({ ...@@ -373,15 +369,17 @@ export default function Image({
} }
const [blurComplete, setBlurComplete] = useState(false) const [blurComplete, setBlurComplete] = useState(false)
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( // React doesn't show the stack trace and there's
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify( // no `src` to help identify which image, so we
{ width, height, quality } // instead console.error(ref) during mount.
)}` unoptimized = true
) } else {
}
if (typeof widthInt === 'undefined') { if (typeof widthInt === 'undefined') {
throw new Error( throw new Error(
`Image with src "${src}" is missing required "width" property.` `Image with src "${src}" is missing required "width" property.`
...@@ -506,6 +504,7 @@ export default function Image({ ...@@ -506,6 +504,7 @@ export default function Image({
} }
} }
} }
}
const imgStyle = Object.assign({}, style) const imgStyle = Object.assign({}, style)
const svgBlurPlaceholder = `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 ${widthInt} ${heightInt}'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='50'/%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1'/%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23b)' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E")` const svgBlurPlaceholder = `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 ${widthInt} ${heightInt}'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='50'/%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1'/%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23b)' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E")`
const blurStyle = const blurStyle =
...@@ -652,6 +651,11 @@ const ImageElement = ({ ...@@ -652,6 +651,11 @@ const ImageElement = ({
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
ref={useCallback( ref={useCallback(
(img: ImgElementWithDataProp) => { (img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
if (img?.complete) { if (img?.complete) {
handleLoading( handleLoading(
img, img,
......
...@@ -429,10 +429,6 @@ export default function Image({ ...@@ -429,10 +429,6 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:') || src.startsWith('blob:')) { if (src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -505,14 +501,19 @@ export default function Image({ ...@@ -505,14 +501,19 @@ export default function Image({
objectPosition, objectPosition,
} }
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( // React doesn't show the stack trace and there's
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify( // no `src` to help identify which image, so we
{ width, height, quality } // instead console.error(ref) during mount.
)}` widthInt = widthInt || 1
) heightInt = heightInt || 1
} unoptimized = true
} else {
if (!VALID_LAYOUT_VALUES.includes(layout)) { if (!VALID_LAYOUT_VALUES.includes(layout)) {
if ((layout as any) === 'raw') { if ((layout as any) === 'raw') {
throw new Error( throw new Error(
...@@ -651,6 +652,7 @@ export default function Image({ ...@@ -651,6 +652,7 @@ export default function Image({
} }
} }
} }
}
const imgStyle = Object.assign({}, style, layoutStyle) const imgStyle = Object.assign({}, style, layoutStyle)
const blurStyle = const blurStyle =
placeholder === 'blur' && !blurComplete placeholder === 'blur' && !blurComplete
...@@ -881,6 +883,11 @@ const ImageElement = ({ ...@@ -881,6 +883,11 @@ const ImageElement = ({
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
ref={useCallback( ref={useCallback(
(img: ImgElementWithDataProp) => { (img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
setIntersection(img) setIntersection(img)
if (img?.complete) { if (img?.complete) {
handleLoading( handleLoading(
......
...@@ -386,10 +386,13 @@ function runTests(mode) { ...@@ -386,10 +386,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/docs/missing-src') const browser = await webdriver(appPort, '/docs/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -746,10 +746,13 @@ function runTests(mode) { ...@@ -746,10 +746,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src') const browser = await webdriver(appPort, '/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -130,10 +130,13 @@ function runTests(mode) { ...@@ -130,10 +130,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/docs/missing-src') const browser = await webdriver(appPort, '/docs/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
...@@ -605,10 +605,13 @@ function runTests(mode) { ...@@ -605,10 +605,13 @@ function runTests(mode) {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src') const browser = await webdriver(appPort, '/missing-src')
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(false)
expect(await getRedboxHeader(browser)).toContain(
'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}' await check(async () => {
) return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image is missing required "src" property/gm)
}) })
it('should show invalid src error', async () => { it('should show invalid src error', async () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment