Unverified Commit 191710dd authored by Steven's avatar Steven Committed by GitHub

Show error message when using legacy props on new `next/image` (#41930)

This PR shows a better error message when using legacy props on new
`next/image` (introduced in Next.js 13) and makes the codemod more
discoverable.
parent 0beed356
...@@ -346,6 +346,10 @@ ...@@ -346,6 +346,10 @@
"title": "next-image-unconfigured-host", "title": "next-image-unconfigured-host",
"path": "/errors/next-image-unconfigured-host.md" "path": "/errors/next-image-unconfigured-host.md"
}, },
{
"title": "next-image-upgrade-to-13",
"path": "/errors/next-image-upgrade-to-13.md"
},
{ {
"title": "next-script-for-ga", "title": "next-script-for-ga",
"path": "/errors/next-script-for-ga.md" "path": "/errors/next-script-for-ga.md"
......
# `next/image` changed in version 13
#### Why This Error Occurred
Starting in Next.js 13, the `next/image` component has undergone some major changes.
Compared to the legacy component, the new `next/image` component has the following changes:
- Removes `<span>` wrapper around `<img>` in favor of [native computed aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes)
- Adds support for canonical `style` prop
- Removes `layout` prop in favor of `style` or `className`
- Removes `objectFit` prop in favor of `style` or `className`
- Removes `objectPosition` prop in favor of `style` or `className`
- Removes `IntersectionObserver` implementation in favor of [native lazy loading](https://caniuse.com/loading-lazy-attr)
- Removes `lazyBoundary` prop since there is no native equivalent
- Removes `lazyRoot` prop since there is no native equivalent
- Removes `loader` config in favor of [`loader`](#loader) prop
- Changed `alt` prop from optional to required
#### Possible Ways to Fix It
Run the [next-image-to-legacy-image](https://nextjs.org/docs/advanced-features/codemods#next-image-to-legacy-image) codemod to automatically change `next/image` imports to `next/legacy/image`, for example:
```
npx @next/codemod next-image-to-legacy-image .
```
After running this codemod, you can optionally upgrade `next/legacy/image` to the new `next/image` with another codemod, for example:
```
npx @next/codemod next-image-experimental .
```
Please note this second codemod is experimental and only covers static usage, not dynamic usage (such `<Image {...props} />`).
### Useful Links
- [Next.js 13 Blog Post](https://nextjs.org/blog/next-13)
- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
- [`next/legacy/image` Documentation](https://nextjs.org/docs/api-reference/next/legacy/image)
...@@ -57,6 +57,12 @@ function findAndReplaceProps( ...@@ -57,6 +57,12 @@ function findAndReplaceProps(
objectPosition = String(a.value.value) objectPosition = String(a.value.value)
return false return false
} }
if (a.name.name === 'lazyBoundary') {
return false
}
if (a.name.name === 'lazyRoot') {
return false
}
if (a.name.name === 'style') { if (a.name.name === 'style') {
if ( if (
......
...@@ -394,24 +394,6 @@ const ImageElement = ({ ...@@ -394,24 +394,6 @@ const ImageElement = ({
if (!srcString) { if (!srcString) {
console.error(`Image is missing required "src" property:`, img) console.error(`Image is missing required "src" property:`, img)
} }
if (
img.getAttribute('objectFit') ||
img.getAttribute('objectfit')
) {
console.error(
`Image has unknown prop "objectFit". Did you mean to use the "style" prop instead?`,
img
)
}
if (
img.getAttribute('objectPosition') ||
img.getAttribute('objectposition')
) {
console.error(
`Image has unknown prop "objectPosition". Did you mean to use the "style" prop instead?`,
img
)
}
if (img.getAttribute('alt') === null) { if (img.getAttribute('alt') === null) {
console.error( console.error(
`Image is missing required "alt" property. Please add Alternative Text to describe the image for screen readers and search engines.` `Image is missing required "alt" property. Please add Alternative Text to describe the image for screen readers and search engines.`
...@@ -560,6 +542,21 @@ export default function Image({ ...@@ -560,6 +542,21 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
for (const legacyProp of [
'layout',
'objectFit',
'objectPosition',
'lazyBoundary',
'lazyRoot',
]) {
if (legacyProp in rest) {
throw new Error(
`Image with src "${src}" has legacy prop "${legacyProp}". Did you forget to run the codemod?` +
`\nRead more: https://nextjs.org/docs/messages/next-image-upgrade-to-13`
)
}
}
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:')) {
......
...@@ -7,12 +7,7 @@ const Page = () => { ...@@ -7,12 +7,7 @@ const Page = () => {
return ( return (
<div> <div>
<h1 id="page-header">Static Image</h1> <h1 id="page-header">Static Image</h1>
<Image <Image id="basic-static" src={testTall} placeholder="blur" />
id="basic-static"
src={testTall}
layout="fixed"
placeholder="blur"
/>
</div> </div>
) )
} }
......
...@@ -7,12 +7,7 @@ const Page = () => { ...@@ -7,12 +7,7 @@ const Page = () => {
return ( return (
<div> <div>
<h1 id="page-header">Static Image</h1> <h1 id="page-header">Static Image</h1>
<Image <Image id="basic-static" src={testTall} placeholder="blur" />
id="basic-static"
src={testTall}
layout="fixed"
placeholder="blur"
/>
</div> </div>
) )
} }
......
...@@ -29,7 +29,6 @@ const Page = () => { ...@@ -29,7 +29,6 @@ const Page = () => {
<ImageWithMessage <ImageWithMessage
id="3" id="3"
src="/test.svg" src="/test.svg"
layout="responsive"
width="1200" width="1200"
height="1200" height="1200"
idToCount={idToCount} idToCount={idToCount}
......
...@@ -15,7 +15,8 @@ const Page = () => { ...@@ -15,7 +15,8 @@ const Page = () => {
width={200} width={200}
height={200} height={200}
src="/test.jpg" src="/test.jpg"
objectFit="cover" fill
style={{ objectFit: 'cover' }}
/> />
<Image <Image
......
...@@ -6,14 +6,7 @@ const Page = () => { ...@@ -6,14 +6,7 @@ const Page = () => {
return ( return (
<> <>
<h1>Warning should print at most once</h1> <h1>Warning should print at most once</h1>
<Image <Image id="w" src="/test.png" width="400" height="400" sizes="50vw" />
id="w"
layout="unknown"
src="/test.png"
width="400"
height="400"
sizes="50vw"
/>
<button onClick={() => setCount(count + 1)}>Count: {count}</button> <button onClick={() => setCount(count + 1)}>Count: {count}</button>
<footer>footer here</footer> <footer>footer here</footer>
</> </>
......
...@@ -912,20 +912,6 @@ function runTests(mode) { ...@@ -912,20 +912,6 @@ function runTests(mode) {
) )
expect(warnings.length).toBe(1) expect(warnings.length).toBe(1)
}) })
it('should show console error for objectFit and objectPosition', async () => {
const browser = await webdriver(appPort, '/invalid-objectfit')
expect(await hasRedbox(browser)).toBe(false)
await check(async () => {
return (await browser.log()).map((log) => log.message).join('\n')
}, /Image has unknown prop "objectFit"/gm)
await check(async () => {
return (await browser.log()).map((log) => log.message).join('\n')
}, /Image has unknown prop "objectPosition"/gm)
})
} else { } else {
//server-only tests //server-only tests
it('should not create an image folder in server/chunks', async () => { it('should not create an image folder in server/chunks', async () => {
......
import React from 'react' import React from 'react'
import Image from 'next/image' import Image from 'next/image'
import logo from '../public/logo.png'
const Page = () => { const Page = () => {
return ( return (
<div> <div>
<Image <h1>Should not use "layout" prop</h1>
src="/test.jpg" <Image id="invalid-layout" layout="responsive" src={logo} />
width="400"
height="400"
objectFit="contain"
objectPosition="20% 20%"
/>
</div> </div>
) )
} }
......
/* eslint-env jest */
import { join } from 'path'
import {
findPort,
hasRedbox,
killApp,
launchApp,
nextBuild,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../')
let appPort: number
let app
let stderr = ''
const msg =
/Error: Image with src "(.*)logo(.*)png" has legacy prop "layout". Did you forget to run the codemod?./
function runTests({ isDev }) {
it('should show error', async () => {
if (isDev) {
const browser = await webdriver(appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(stderr).toMatch(msg)
} else {
expect(stderr).toMatch(msg)
}
})
}
describe('Missing Import Image Tests', () => {
describe('dev mode', () => {
beforeAll(async () => {
stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
})
afterAll(async () => {
if (app) {
await killApp(app)
}
})
runTests({ isDev: true })
})
describe('server mode', () => {
beforeAll(async () => {
stderr = ''
const result = await nextBuild(appDir, [], { stderr: true })
stderr = result.stderr
})
afterAll(async () => {
if (app) {
await killApp(app)
}
})
runTests({ isDev: false })
})
})
import React from 'react'
import Image from 'next/image'
import logo from '../public/logo.png'
const Page = () => {
return (
<div>
<h1>Should not use "objectFit" prop</h1>
<Image id="invalid-layout" objectFit="contain" src={logo} />
</div>
)
}
export default Page
/* eslint-env jest */
import { join } from 'path'
import {
findPort,
hasRedbox,
killApp,
launchApp,
nextBuild,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../')
let appPort: number
let app
let stderr = ''
const msg =
/Error: Image with src "(.*)logo(.*)png" has legacy prop "objectFit". Did you forget to run the codemod?./
function runTests({ isDev }) {
it('should show error', async () => {
if (isDev) {
const browser = await webdriver(appPort, '/')
expect(await hasRedbox(browser, true)).toBe(true)
expect(stderr).toMatch(msg)
} else {
expect(stderr).toMatch(msg)
}
})
}
describe('Missing Import Image Tests', () => {
describe('dev mode', () => {
beforeAll(async () => {
stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
})
afterAll(async () => {
if (app) {
await killApp(app)
}
})
runTests({ isDev: true })
})
describe('server mode', () => {
beforeAll(async () => {
stderr = ''
const result = await nextBuild(appDir, [], { stderr: true })
stderr = result.stderr
})
afterAll(async () => {
if (app) {
await killApp(app)
}
})
runTests({ isDev: false })
})
})
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