Unverified Commit 676be08d authored by Steven's avatar Steven Committed by GitHub

Warn when legacy prop detected on `next/image` (#42102)

Instead of hard error, we can try to convert legacy props to the new
props and print a warning.

We still recommend upgrading by running one (or both) codemods because
the new component no longer has a wrapping `<span>`.

<img width="616" alt="image"
src="https://user-images.githubusercontent.com/229881/198756393-7d981686-f4db-485b-9f5f-1ff614d35959.png">

Read more: https://nextjs.org/docs/messages/next-image-upgrade-to-13
parent f355dd4f
...@@ -108,6 +108,27 @@ export type ImageProps = Omit< ...@@ -108,6 +108,27 @@ export type ImageProps = Omit<
blurDataURL?: string blurDataURL?: string
unoptimized?: boolean unoptimized?: boolean
onLoadingComplete?: OnLoadingComplete onLoadingComplete?: OnLoadingComplete
/**
* @deprecated Use `fill` prop instead of `layout="fill"` or change import to `next/legacy/image`.
* @see https://nextjs.org/docs/api-reference/next/legacy/image
*/
layout?: string
/**
* @deprecated Use `style` prop instead.
*/
objectFit?: string
/**
* @deprecated Use `style` prop instead.
*/
objectPosition?: string
/**
* @deprecated This prop does not do anything.
*/
lazyBoundary?: string
/**
* @deprecated This prop does not do anything.
*/
lazyRoot?: string
} }
type ImageElementProps = Omit<ImageProps, 'src' | 'alt' | 'loader'> & { type ImageElementProps = Omit<ImageProps, 'src' | 'alt' | 'loader'> & {
...@@ -467,6 +488,11 @@ export default function Image({ ...@@ -467,6 +488,11 @@ export default function Image({
onLoadingComplete, onLoadingComplete,
placeholder = 'empty', placeholder = 'empty',
blurDataURL, blurDataURL,
layout,
objectFit,
objectPosition,
lazyBoundary,
lazyRoot,
...all ...all
}: ImageProps) { }: ImageProps) {
const configContext = useContext(ImageConfigContext) const configContext = useContext(ImageConfigContext)
...@@ -479,7 +505,6 @@ export default function Image({ ...@@ -479,7 +505,6 @@ export default function Image({
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
let loader: ImageLoaderWithConfig = rest.loader || defaultLoader let loader: ImageLoaderWithConfig = rest.loader || defaultLoader
// Remove property so it's not spread on <img> element // Remove property so it's not spread on <img> element
delete rest.loader delete rest.loader
...@@ -503,6 +528,28 @@ export default function Image({ ...@@ -503,6 +528,28 @@ export default function Image({
} }
} }
if (layout) {
if (layout === 'fill') {
fill = true
}
const layoutToStyle: Record<string, Record<string, string> | undefined> = {
intrinsic: { maxWidth: '100%', height: 'auto' },
responsive: { width: '100%', height: 'auto' },
}
const layoutToSizes: Record<string, string | undefined> = {
responsive: '100vw',
fill: '100vw',
}
const layoutStyle = layoutToStyle[layout]
if (layoutStyle) {
style = { ...style, ...layoutStyle }
}
const layoutSizes = layoutToSizes[layout]
if (layoutSizes && !sizes) {
sizes = layoutSizes
}
}
let staticSrc = '' let staticSrc = ''
let widthInt = getInt(width) let widthInt = getInt(width)
let heightInt = getInt(height) let heightInt = getInt(height)
...@@ -546,21 +593,6 @@ export default function Image({ ...@@ -546,21 +593,6 @@ 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:')) {
...@@ -691,6 +723,21 @@ export default function Image({ ...@@ -691,6 +723,21 @@ export default function Image({
} }
} }
for (const [legacyKey, legacyValue] of Object.entries({
layout,
objectFit,
objectPosition,
lazyBoundary,
lazyRoot,
})) {
if (legacyValue) {
warnOnce(
`Image with src "${src}" has legacy prop "${legacyKey}". Did you forget to run the codemod?` +
`\nRead more: https://nextjs.org/docs/messages/next-image-upgrade-to-13`
)
}
}
if ( if (
typeof window !== 'undefined' && typeof window !== 'undefined' &&
!perfObserver && !perfObserver &&
...@@ -737,6 +784,8 @@ export default function Image({ ...@@ -737,6 +784,8 @@ export default function Image({
top: 0, top: 0,
right: 0, right: 0,
bottom: 0, bottom: 0,
objectFit,
objectPosition,
} }
: {}, : {},
showAltText ? {} : { color: 'transparent' }, showAltText ? {} : { color: 'transparent' },
......
import Image from 'next/image'
export default function Page() {
return (
<div className="page">
<h1>Using legacy prop layout="fill"</h1>
<p>
Even though we don't support "layout" in next/image, we can try to
correct the style and print a warning.
</p>
<div style={{ position: 'relative', width: '200px', height: '400px' }}>
<Image
id="img"
layout="fill"
src="/test.jpg"
alt="my fill image"
quality={50}
objectFit="cover"
objectPosition="10% 10%"
sizes="200px"
priority
/>
</div>
</div>
)
}
import Image from 'next/image'
export default function Page() {
return (
<div className="page">
<h1>Using legacy prop layout="responsive"</h1>
<p>
Even though we don't support "layout" in next/image, we can try to
correct the style and print a warning.
</p>
<Image
id="img"
layout="responsive"
src="/test.png"
width="100"
height="100"
alt="my responsive image"
priority
/>
</div>
)
}
...@@ -669,6 +669,64 @@ function runTests(mode) { ...@@ -669,6 +669,64 @@ function runTests(mode) {
).toBe('color:transparent') ).toBe('color:transparent')
}) })
it('should warn when legacy prop layout=fill', async () => {
let browser = await webdriver(appPort, '/legacy-layout-fill')
const img = await browser.elementById('img')
expect(img).toBeDefined()
expect(await img.getAttribute('data-nimg')).toBe('fill')
expect(await img.getAttribute('sizes')).toBe('200px')
expect(await img.getAttribute('src')).toBe(
'/_next/image?url=%2Ftest.jpg&w=3840&q=50'
)
expect(await img.getAttribute('srcset')).toContain(
'/_next/image?url=%2Ftest.jpg&w=640&q=50 640w,'
)
expect(await img.getAttribute('style')).toBe(
'position:absolute;height:100%;width:100%;left:0;top:0;right:0;bottom:0;object-fit:cover;object-position:10% 10%;color:transparent'
)
if (mode === 'dev') {
expect(await hasRedbox(browser)).toBe(false)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
expect(warnings).toContain(
'Image with src "/test.jpg" has legacy prop "layout". Did you forget to run the codemod?'
)
expect(warnings).toContain(
'Image with src "/test.jpg" has legacy prop "objectFit". Did you forget to run the codemod?'
)
expect(warnings).toContain(
'Image with src "/test.jpg" has legacy prop "objectPosition". Did you forget to run the codemod?'
)
}
})
it('should warn when legacy prop layout=responsive', async () => {
let browser = await webdriver(appPort, '/legacy-layout-responsive')
const img = await browser.elementById('img')
expect(img).toBeDefined()
expect(await img.getAttribute('sizes')).toBe('100vw')
expect(await img.getAttribute('data-nimg')).toBe('1')
expect(await img.getAttribute('src')).toBe(
'/_next/image?url=%2Ftest.png&w=3840&q=75'
)
expect(await img.getAttribute('srcset')).toContain(
'/_next/image?url=%2Ftest.png&w=640&q=75 640w,'
)
expect(await img.getAttribute('style')).toBe(
'color:transparent;width:100%;height:auto'
)
if (mode === 'dev') {
expect(await hasRedbox(browser)).toBe(false)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
expect(warnings).toContain(
'Image with src "/test.png" has legacy prop "layout". Did you forget to run the codemod?'
)
}
})
if (mode === 'dev') { if (mode === 'dev') {
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')
......
import React from 'react'
import Image from 'next/image'
import logo from '../public/logo.png'
const Page = () => {
return (
<div>
<h1>Should not use "layout" prop</h1>
<Image id="invalid-layout" layout="responsive" 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 "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