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

Update `next/image` docs and examples (#41434)

This PR updates the docs for the following code change:

- #41399

There are a few updates here:

- [x] Update docs
- [x] Update links to docs inside component
- [x] Update examples
- [x] Fix corner cases in codemod
parent e61820e0
...@@ -64,7 +64,97 @@ Dangerously migrates from `next/legacy/image` to the new `next/image` by adding ...@@ -64,7 +64,97 @@ Dangerously migrates from `next/legacy/image` to the new `next/image` by adding
- Removes `objectPosition` prop and adds `style` - Removes `objectPosition` prop and adds `style`
- Removes `lazyBoundary` prop - Removes `lazyBoundary` prop
- Removes `lazyRoot` prop - Removes `lazyRoot` prop
- TODO: handle `loader` - TODO: does not migrate the `loader` config. If you need it, you must manually add a `loader` prop.
#### Before: intrinsic
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} />
}
```
#### After: intrinsic
```jsx
import Image from 'next/image'
import img from '../img.png'
const css = { maxWidth: '100%', height: 'auto' }
function Page() {
return <Image src={img} style={css} />
}
```
#### Before: responsive
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} layout="responsive" />
}
```
#### After: responsive
```jsx
import Image from 'next/image'
import img from '../img.png'
const css = { width: '100%', height: 'auto' }
function Page() {
return <Image src={img} sizes="100vw" style={css} />
}
```
#### Before: fill
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} layout="fill" />
}
```
#### After: fill
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} sizes="100vw" fill />
}
```
#### Before: fixed
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} layout="fixed" />
}
```
#### After: fixed
```jsx
import Image from 'next/image'
import img from '../img.png'
function Page() {
return <Image src={img} />
}
```
## Next.js 11 ## Next.js 11
......
This diff is collapsed.
...@@ -28,12 +28,6 @@ To add an image to your application, import the [`next/image`](/docs/api-referen ...@@ -28,12 +28,6 @@ To add an image to your application, import the [`next/image`](/docs/api-referen
import Image from 'next/image' import Image from 'next/image'
``` ```
Alternatively, you can import [`next/future/image`](/docs/api-reference/next/future/image.md) if you need a component much closer to the native `<img>` element:
```jsx
import Image from 'next/future/image'
```
Now, you can define the `src` for your image (either local or remote). Now, you can define the `src` for your image (either local or remote).
### Local Images ### Local Images
...@@ -151,15 +145,15 @@ Because `next/image` is designed to guarantee good performance results, it canno ...@@ -151,15 +145,15 @@ Because `next/image` is designed to guarantee good performance results, it canno
1. Automatically, using a [static import](#local-images) 1. Automatically, using a [static import](#local-images)
2. Explicitly, by including a [`width`](/docs/api-reference/next/image.md#width) and [`height`](/docs/api-reference/next/image.md#height) property 2. Explicitly, by including a [`width`](/docs/api-reference/next/image.md#width) and [`height`](/docs/api-reference/next/image.md#height) property
3. Implicitly, by using [`layout="fill"`](/docs/api-reference/next/image.md#layout) which causes the image to expand to fill its parent element. 3. Implicitly, by using [fill](/docs/api-reference/next/image.md#fill) which causes the image to expand to fill its parent element.
> ### What if I don't know the size of my images? > ### What if I don't know the size of my images?
> >
> If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do: > If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do:
> >
> **Use `layout='fill'`** > **Use `fill``**
> >
> The `fill` layout mode allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page, then using the [`objectFit property`](/docs/api-reference/next/image.md#objectfit) with `fill`, `contain`, or `cover`, along with the [`objectPosition property`](/docs/api-reference/next/image.md#objectposition) to define how the image should occupy that space. > The [`fill`](/docs/api-reference/next/image#fill) prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along [`sizes`](/docs/api-reference/next/image#sizes) prop to match any media query break points. You can also use [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) with `fill`, `contain`, or `cover`, and [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) to define how the image should occupy that space.
> >
> **Normalize your images** > **Normalize your images**
> >
...@@ -175,27 +169,21 @@ If none of the suggested methods works for sizing your images, the `next/image` ...@@ -175,27 +169,21 @@ If none of the suggested methods works for sizing your images, the `next/image`
> Note: Many of the styling issues listed below can be solved with [`next/future/image`](/docs/api-reference/next/future/image.md) > Note: Many of the styling issues listed below can be solved with [`next/future/image`](/docs/api-reference/next/future/image.md)
Styling the Image component is not that different from styling a normal `<img>` element, but there are a few guidelines to keep in mind: Styling the Image component is similar to styling a normal `<img>` element, but there are a few guidelines to keep in mind:
**Pick the correct layout mode**
The image component has several different [layout modes](/docs/api-reference/next/image.md#layout) that define how it is sized on the page. If the styling of your image isn't turning out the way you want, consider experimenting with other layout modes.
**Target the image with className, not based on DOM structure**
For most layout modes, the Image component will have a DOM structure of one `<img>` tag wrapped by exactly one `<span>`. For some modes, it may also have a sibling `<span>` for spacing. These additional `<span>` elements are critical to allow the component to prevent layout shifts. **Use `className` or `style`, not `styled-jsx`**
The recommended way to style the inner `<img>` is to set the `className` prop on the Image component to the value of an imported [CSS Module](/docs/basic-features/built-in-css-support.md#adding-component-level-css). The value of `className` will be automatically applied to the underlying `<img>` element. In most cases, we recommend using the `className` prop. This can be an imported [CSS Module](/docs/basic-features/built-in-css-support.md#adding-component-level-css), a [global stylesheet](/docs/basic-features/built-in-css-support#adding-a-global-stylesheet), etc.
Alternatively, you can import a [global stylesheet](/docs/basic-features/built-in-css-support#adding-a-global-stylesheet) and manually set the `className` prop to the same name used in the global stylesheet. You can also use the `style` prop to assign inline styles.
You cannot use [styled-jsx](/docs/basic-features/built-in-css-support.md#css-in-js) because it's scoped to the current component. You cannot use [styled-jsx](/docs/basic-features/built-in-css-support.md#css-in-js) because it's scoped to the current component (unless you mark the style as `global`).
**When using `layout='fill'`, the parent element must have `position: relative`** **When using `fill`, the parent element must have `position: relative`**
This is necessary for the proper rendering of the image element in that layout mode. This is necessary for the proper rendering of the image element in that layout mode.
**When using `layout='responsive'`, the parent element must have `display: block`** **When using `fill`, the parent element must have `display: block`**
This is the default for `<div>` elements but should be specified otherwise. This is the default for `<div>` elements but should be specified otherwise.
...@@ -205,7 +193,7 @@ This is the default for `<div>` elements but should be specified otherwise. ...@@ -205,7 +193,7 @@ This is the default for `<div>` elements but should be specified otherwise.
### Styling Examples ### Styling Examples
For examples of the Image component used with the various fill modes, see the [Image component example app](https://image-component.nextjs.gallery/). For examples of the Image component used with the various styles, see the [Image component example app](https://image-component.nextjs.gallery).
## Configuration ## Configuration
......
...@@ -427,8 +427,14 @@ ...@@ -427,8 +427,14 @@
} }
}, },
{ {
"title": "next/future/image", "path": "/docs/api-reference/next/future/image",
"path": "/docs/api-reference/next/future/image.md" "redirect": {
"destination": "/docs/api-reference/next/image"
}
},
{
"title": "next/legacy/image",
"path": "/docs/api-reference/next/legacy/image.md"
}, },
{ {
"title": "Edge Runtime", "title": "Edge Runtime",
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
images: { images: {
domains: ['assets.vercel.com'],
formats: ['image/avif', 'image/webp'], formats: ['image/avif', 'image/webp'],
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.vercel.com',
port: '',
pathname: '/image/upload/**',
},
],
}, },
} }
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"next": "latest", "next": "canary",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
}, },
......
import Image from 'next/image' import Image from 'next/image'
import ViewSource from '../components/view-source' import ViewSource from '../components/view-source'
import styles from '../styles.module.css' import styles from '../styles.module.css'
import mountains from '../public/mountains.jpg'
const BackgroundPage = () => ( const BackgroundPage = () => (
<div> <div>
...@@ -8,10 +9,14 @@ const BackgroundPage = () => ( ...@@ -8,10 +9,14 @@ const BackgroundPage = () => (
<div className={styles.bgWrap}> <div className={styles.bgWrap}>
<Image <Image
alt="Mountains" alt="Mountains"
src="/mountains.jpg" src={mountains}
layout="fill" placeholder="blur"
objectFit="cover"
quality={100} quality={100}
fill
sizes="100vw"
style={{
objectFit: 'cover',
}}
/> />
</div> </div>
<p className={styles.bgText}> <p className={styles.bgText}>
......
...@@ -27,6 +27,10 @@ const Color = () => ( ...@@ -27,6 +27,10 @@ const Color = () => (
blurDataURL={rgbDataURL(237, 181, 6)} blurDataURL={rgbDataURL(237, 181, 6)}
width={750} width={750}
height={1000} height={1000}
style={{
maxWidth: '100%',
height: 'auto',
}}
/> />
<Image <Image
alt="Cat" alt="Cat"
...@@ -35,6 +39,10 @@ const Color = () => ( ...@@ -35,6 +39,10 @@ const Color = () => (
blurDataURL={rgbDataURL(2, 129, 210)} blurDataURL={rgbDataURL(2, 129, 210)}
width={750} width={750}
height={1000} height={1000}
style={{
maxWidth: '100%',
height: 'auto',
}}
/> />
</div> </div>
) )
......
import Image from 'next/image'
import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg'
const Fill = () => (
<div>
<ViewSource pathname="pages/layout-fill.tsx" />
<h1>Image Component With Layout Fill</h1>
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
alt="Mountains"
src={mountains}
fill
sizes="100vw"
style={{
objectFit: 'cover',
}}
/>
</div>
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
alt="Mountains"
src={mountains}
fill
sizes="100vw"
style={{
objectFit: 'contain',
}}
/>
</div>
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
alt="Mountains"
src={mountains}
quality={100}
fill
sizes="100vw"
style={{
objectFit: 'none',
}}
/>
</div>
</div>
)
export default Fill
...@@ -29,70 +29,40 @@ const Index = () => ( ...@@ -29,70 +29,40 @@ const Index = () => (
images on-demand as the browser requests them. images on-demand as the browser requests them.
</p> </p>
<hr className={styles.hr} /> <hr className={styles.hr} />
<h2 id="layout">Layout</h2> <h2 id="examples">Examples</h2>
<p> <p>
The <Code>layout</Code> property tells the image to respond differently Try it the examples below (you may need to disable cache in dev tools to
depending on the device size or the container size. see the effect if you already visited):
</p>
<p>
Select a layout below and try resizing the window or rotating your
device to see how the image reacts.
</p> </p>
<ul> <ul>
<li> <li>
<Link href="/layout-intrinsic"> <Link href="/responsive">
<a>layout="intrinsic"</a> <a>Responsive to viewport</a>
</Link>
</li>
<li>
<Link href="/layout-responsive">
<a>layout="responsive"</a>
</Link>
</li>
<li>
<Link href="/layout-fixed">
<a>layout="fixed"</a>
</Link> </Link>
</li> </li>
<li> <li>
<Link href="/layout-fill"> <Link href="/fill">
<a>layout="fill"</a> <a>Fill dimensions of parent element</a>
</Link> </Link>
</li> </li>
<li>
<Link href="/background">
<a>background demo</a>
</Link>
</li>
</ul>
<hr className={styles.hr} />
<h2 id="placeholder">Placeholder</h2>
<p>
The <Code>placeholder</Code> property tells the image what to do while
loading.
</p>
<p>
You can optionally enable a blur-up placeholder while the high
resolution image loads.
</p>
<p>
Try it out below (you may need to disable cache in dev tools to see the
effect if you already visited):
</p>
<ul>
<li> <li>
<Link href="/placeholder"> <Link href="/placeholder">
<a>placeholder="blur"</a> <a>Blur-up placeholder</a>
</Link> </Link>
</li> </li>
<li> <li>
<Link href="/shimmer"> <Link href="/shimmer">
<a>placeholder="blur" with animated shimmer blurDataURL</a> <a>Shimmer placeholder</a>
</Link> </Link>
</li> </li>
<li> <li>
<Link href="/color"> <Link href="/color">
<a>placeholder="blur" with solid color blurDataURL</a> <a>Color placeholder</a>
</Link>
</li>
<li>
<Link href="/background">
<a>Text on background image</a>
</Link> </Link>
</li> </li>
</ul> </ul>
...@@ -106,7 +76,16 @@ const Index = () => ( ...@@ -106,7 +76,16 @@ const Index = () => (
This image is intentionally large so you have to scroll down to the next This image is intentionally large so you have to scroll down to the next
image. image.
</p> </p>
<Image alt="Vercel logo" src={vercel} width={1000} height={1000} /> <Image
alt="Vercel logo"
src={vercel}
width={1000}
height={1000}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
<hr className={styles.hr} /> <hr className={styles.hr} />
<h2 id="external">External Image</h2> <h2 id="external">External Image</h2>
<p> <p>
...@@ -114,14 +93,18 @@ const Index = () => ( ...@@ -114,14 +93,18 @@ const Index = () => (
<Code>assets.vercel.com</Code>. <Code>assets.vercel.com</Code>.
</p> </p>
<p> <p>
External domains must be configured in <Code>next.config.js</Code> using External images must be configured in <Code>next.config.js</Code> using
the <Code>domains</Code> property. the <Code>remotePatterns</Code> property.
</p> </p>
<Image <Image
alt="Next.js logo" alt="Next.js logo"
src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png" src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png"
width={1200} width={1200}
height={400} height={400}
style={{
maxWidth: '100%',
height: 'auto',
}}
/> />
<hr className={styles.hr} /> <hr className={styles.hr} />
<h2 id="more">Learn More</h2> <h2 id="more">Learn More</h2>
......
...@@ -12,6 +12,10 @@ const PlaceholderBlur = () => ( ...@@ -12,6 +12,10 @@ const PlaceholderBlur = () => (
placeholder="blur" placeholder="blur"
width={700} width={700}
height={475} height={475}
style={{
maxWidth: '100%',
height: 'auto',
}}
/> />
</div> </div>
) )
......
import Image from 'next/image'
import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg'
const Responsive = () => (
<div>
<ViewSource pathname="pages/layout-responsive.tsx" />
<h1>Image Component With Layout Responsive</h1>
<Image
alt="Mountains"
src={mountains}
width={700}
height={475}
sizes="100vw"
style={{
width: '100%',
height: 'auto',
}}
/>
</div>
)
export default Responsive
...@@ -31,6 +31,10 @@ const Shimmer = () => ( ...@@ -31,6 +31,10 @@ const Shimmer = () => (
blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`} blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`}
width={700} width={700}
height={475} height={475}
style={{
maxWidth: '100%',
height: 'auto',
}}
/> />
</div> </div>
) )
......
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
"module": "esnext", "module": "esnext",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve" "jsx": "preserve",
"moduleResolution": "node"
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Image Component Example
This example shows how to use the [Image Component in Next.js](https://nextjs.org/docs/api-reference/next/image) serve optimized, responsive images.
The index page ([`pages/index.js`](pages/index.js)) has a couple images, one internal image and one external image. In [`next.config.js`](next.config.js), the `domains` property is used to enable external images. The other pages demonstrate the different layouts. Run or deploy the app to see how it works!
## Live demo
[https://image-component.nextjs.gallery/](https://image-component.nextjs.gallery/)
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/image-legacy-component)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/image-component&project-name=image-component&repository-name=image-legacy-component)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example image-component image-app
# or
yarn create next-app --example image-component image-app
# or
pnpm create next-app --example image-component image-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
body {
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
margin: 0;
padding: 0;
background: black;
color: white;
}
a {
cursor: pointer;
color: #0076ff;
text-decoration: none;
transition: all 0.2s ease;
border-bottom: 1px solid black;
}
a:hover {
border-bottom: 1px solid #0076ff;
}
.svg {
position: absolute;
top: 0;
right: 0;
}
.arm {
transform-origin: 130px 106px;
}
.svg:hover .arm {
animation: wave 560ms ease-in-out;
}
@keyframes wave {
0% {
transform: rotate(0deg);
}
20% {
transform: rotate(-25deg);
}
40% {
transform: rotate(10deg);
}
60% {
transform: rotate(-25deg);
}
80% {
transform: rotate(10deg);
}
100% {
transform: rotate(0deg);
}
}
@media (max-width: 500px) {
.svg:hover .arm {
animation: none;
}
.svg:hover .arm {
animation: wave 560ms ease-in-out;
}
}
import styles from './view-source.module.css'
type ViewSourceProps = {
pathname: string
}
const ViewSource = ({ pathname }: ViewSourceProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="80"
height="80"
viewBox="0 0 250 250"
fill="#151513"
className={styles.svg}
>
<a
title="View Source"
href={`https://github.com/vercel/next.js/tree/canary/examples/image-legacy-component/${pathname}`}
>
<path d="M0 0l115 115h15l12 27 108 108V0z" fill="#fff" />
<path
className={styles.arm}
d="M128 109c-15-9-9-19-9-19 3-7 2-11 2-11-1-7 3-2 3-2 4 5 2 11 2 11-3 10 5 15 9 16"
/>
<path d="M115 115s4 2 5 0l14-14c3-2 6-3 8-3-8-11-15-24 2-41 5-5 10-7 16-7 1-2 3-7 12-11 0 0 5 3 7 16 4 2 8 5 12 9s7 8 9 12c14 3 17 7 17 7-4 8-9 11-11 11 0 6-2 11-7 16-16 16-30 10-41 2 0 3-1 7-5 11l-12 11c-1 1 1 5 1 5z" />
</a>
</svg>
)
export default ViewSource
/** @type {import('next').NextConfig} */
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.vercel.com',
port: '',
pathname: '/image/upload/**',
},
],
},
}
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "canary",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "18.7.14",
"@types/react": "16.9.17",
"typescript": "4.8.2"
}
}
import type { AppProps } from 'next/app'
import '../app.css'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
import Image from 'next/legacy/image'
import ViewSource from '../components/view-source'
import styles from '../styles.module.css'
const BackgroundPage = () => (
<div>
<ViewSource pathname="pages/background.tsx" />
<div className={styles.bgWrap}>
<Image
alt="Mountains"
src="/mountains.jpg"
layout="fill"
objectFit="cover"
quality={100}
/>
</div>
<p className={styles.bgText}>
Image Component
<br />
as a Background
</p>
</div>
)
export default BackgroundPage
import Image from 'next/legacy/image'
import ViewSource from '../components/view-source'
// Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535
const keyStr =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
const triplet = (e1: number, e2: number, e3: number) =>
keyStr.charAt(e1 >> 2) +
keyStr.charAt(((e1 & 3) << 4) | (e2 >> 4)) +
keyStr.charAt(((e2 & 15) << 2) | (e3 >> 6)) +
keyStr.charAt(e3 & 63)
const rgbDataURL = (r: number, g: number, b: number) =>
`data:image/gif;base64,R0lGODlhAQABAPAA${
triplet(0, r, g) + triplet(b, 255, 255)
}/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`
const Color = () => (
<div>
<ViewSource pathname="pages/color.tsx" />
<h1>Image Component With Color Data URL</h1>
<Image
alt="Dog"
src="/dog.jpg"
placeholder="blur"
blurDataURL={rgbDataURL(237, 181, 6)}
width={750}
height={1000}
/>
<Image
alt="Cat"
src="/cat.jpg"
placeholder="blur"
blurDataURL={rgbDataURL(2, 129, 210)}
width={750}
height={1000}
/>
</div>
)
export default Color
import styles from '../styles.module.css'
import Image from 'next/legacy/image'
import Link from 'next/link'
import ViewSource from '../components/view-source'
import vercel from '../public/vercel.png'
import type { PropsWithChildren } from 'react'
const Code = (props: PropsWithChildren<{}>) => (
<code className={styles.inlineCode} {...props} />
)
const Index = () => (
<div className={styles.container}>
<ViewSource pathname="pages/index.tsx" />
<div className={styles.card}>
<h1>Image Component with Next.js</h1>
<p>
This page demonstrates the usage of the{' '}
<a href="https://nextjs.org/docs/api-reference/next/legacy/image">
next/legacy/image
</a>{' '}
component with live examples.
</p>
<p>
This component is designed to{' '}
<a href="https://nextjs.org/docs/basic-features/image-optimization">
automatically optimize
</a>{' '}
images on-demand as the browser requests them.
</p>
<hr className={styles.hr} />
<h2 id="layout">Layout</h2>
<p>
External images must be configured in <Code>next.config.js</Code> using
the <Code>remotePatterns</Code> property.
</p>
<p>
Select a layout below and try resizing the window or rotating your
device to see how the image reacts.
</p>
<ul>
<li>
<Link href="/layout-intrinsic">
<a>layout="intrinsic"</a>
</Link>
</li>
<li>
<Link href="/layout-responsive">
<a>layout="responsive"</a>
</Link>
</li>
<li>
<Link href="/layout-fixed">
<a>layout="fixed"</a>
</Link>
</li>
<li>
<Link href="/layout-fill">
<a>layout="fill"</a>
</Link>
</li>
<li>
<Link href="/background">
<a>background demo</a>
</Link>
</li>
</ul>
<hr className={styles.hr} />
<h2 id="placeholder">Placeholder</h2>
<p>
The <Code>placeholder</Code> property tells the image what to do while
loading.
</p>
<p>
You can optionally enable a blur-up placeholder while the high
resolution image loads.
</p>
<p>
Try it out below (you may need to disable cache in dev tools to see the
effect if you already visited):
</p>
<ul>
<li>
<Link href="/placeholder">
<a>placeholder="blur"</a>
</Link>
</li>
<li>
<Link href="/shimmer">
<a>placeholder="blur" with animated shimmer blurDataURL</a>
</Link>
</li>
<li>
<Link href="/color">
<a>placeholder="blur" with solid color blurDataURL</a>
</Link>
</li>
</ul>
<hr className={styles.hr} />
<h2 id="internal">Internal Image</h2>
<p>
The following is an example of a reference to an internal image from the{' '}
<Code>public</Code> directory.
</p>
<p>
This image is intentionally large so you have to scroll down to the next
image.
</p>
<Image alt="Vercel logo" src={vercel} width={1000} height={1000} />
<hr className={styles.hr} />
<h2 id="external">External Image</h2>
<p>
The following is an example of a reference to an external image at{' '}
<Code>assets.vercel.com</Code>.
</p>
<p>
External images must be configured in <Code>next.config.js</Code> using
the <Code>remotePatterns</Code> property.
</p>
<Image
alt="Next.js logo"
src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png"
width={1200}
height={400}
/>
<hr className={styles.hr} />
<h2 id="more">Learn More</h2>
<p>
You can optionally configure a cloud provider, device sizes, and more!
</p>
<p>
Checkout the{' '}
<a href="https://nextjs.org/docs/basic-features/image-optimization">
Image Optimization documentation
</a>{' '}
to learn more.
</p>
</div>
</div>
)
export default Index
import Image from 'next/image' import Image from 'next/legacy/image'
import ViewSource from '../components/view-source' import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg' import mountains from '../public/mountains.jpg'
......
import Image from 'next/image' import Image from 'next/legacy/image'
import ViewSource from '../components/view-source' import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg' import mountains from '../public/mountains.jpg'
......
import Image from 'next/image' import Image from 'next/legacy/image'
import ViewSource from '../components/view-source' import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg' import mountains from '../public/mountains.jpg'
......
import Image from 'next/image' import Image from 'next/legacy/image'
import ViewSource from '../components/view-source' import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg' import mountains from '../public/mountains.jpg'
......
import Image from 'next/legacy/image'
import ViewSource from '../components/view-source'
import mountains from '../public/mountains.jpg'
const PlaceholderBlur = () => (
<div>
<ViewSource pathname="pages/placeholder.tsx" />
<h1>Image Component With Placeholder Blur</h1>
<Image
alt="Mountains"
src={mountains}
placeholder="blur"
width={700}
height={475}
/>
</div>
)
export default PlaceholderBlur
import Image from 'next/legacy/image'
import ViewSource from '../components/view-source'
const shimmer = (w: number, h: number) => `
<svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="g">
<stop stop-color="#333" offset="20%" />
<stop stop-color="#222" offset="50%" />
<stop stop-color="#333" offset="70%" />
</linearGradient>
</defs>
<rect width="${w}" height="${h}" fill="#333" />
<rect id="r" width="${w}" height="${h}" fill="url(#g)" />
<animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite" />
</svg>`
const toBase64 = (str: string) =>
typeof window === 'undefined'
? Buffer.from(str).toString('base64')
: window.btoa(str)
const Shimmer = () => (
<div>
<ViewSource pathname="pages/shimmer.tsx" />
<h1>Image Component With Shimmer Data URL</h1>
<Image
alt="Mountains"
src="/mountains.jpg"
placeholder="blur"
blurDataURL={`data:image/svg+xml;base64,${toBase64(shimmer(700, 475))}`}
width={700}
height={475}
/>
</div>
)
export default Shimmer
.container {
padding: 4rem 1rem;
}
.container p {
margin: 1.5rem 0;
}
.card {
max-width: 60rem;
box-shadow: -10px 10px 80px rgba(255, 255, 255, 0.1);
border: 1px solid #333;
border-radius: 8px;
padding: 2rem;
margin: 0 auto;
}
.inlineCode {
color: #be00ff;
font-size: 16px;
white-space: pre-wrap;
}
.inlineCode::before,
.inlineCode::after {
content: '`';
}
.hr {
border: 0;
border-top: 1px solid #333;
margin: 1.5rem 0;
}
.bgWrap {
position: fixed;
height: 100vh;
width: 100vw;
overflow: hidden;
z-index: -1;
}
.bgText {
margin: 0;
font-size: 2rem;
line-height: 3rem;
text-align: center;
padding-top: 40vh;
text-shadow: 1px 1px 1px #3c5c5e;
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
...@@ -124,6 +124,14 @@ const TRANSFORMER_INQUIRER_CHOICES = [ ...@@ -124,6 +124,14 @@ const TRANSFORMER_INQUIRER_CHOICES = [
name: 'new-link: Ensures your <Link> usage is backwards compatible. Used in combination with experimental newNextLinkBehavior', name: 'new-link: Ensures your <Link> usage is backwards compatible. Used in combination with experimental newNextLinkBehavior',
value: 'new-link', value: 'new-link',
}, },
{
name: 'next-image-to-legacy-image: safely migrate Next.js 10, 11, 12 applications importing `next/image` to the renamed `next/legacy/image` import in Next.js 13',
value: 'next-image-to-legacy-image',
},
{
name: 'next-image-experimental (experimental): dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props',
value: 'next-image-experimental',
},
] ]
function expandFilePathsIfNeeded(filesBeforeExpansion) { function expandFilePathsIfNeeded(filesBeforeExpansion) {
......
...@@ -8,8 +8,8 @@ export default function Home() { ...@@ -8,8 +8,8 @@ export default function Home() {
return ( return (
<div> <div>
<h1>Upgrade</h1> <h1>Upgrade</h1>
<Image src="/test.jpg" width="200" height="300" /> <Image src="/test.jpg" width="100" height="200" />
<Image src="/test.jpg" width="200" height="300" layout="intrinsic" /> <Image src="/test.jpg" width="300" height="400" layout="intrinsic" />
<Image src="/test.jpg" width="200" height="300" layout="responsive" /> <Image src="/test.jpg" width="200" height="300" layout="responsive" />
<Image src="/test.jpg" width="200" height="300" layout="fixed" /> <Image src="/test.jpg" width="200" height="300" layout="fixed" />
<div style={{ position: 'relative', width: '300px', height: '500px' }}> <div style={{ position: 'relative', width: '300px', height: '500px' }}>
......
...@@ -8,11 +8,18 @@ export default function Home() { ...@@ -8,11 +8,18 @@ export default function Home() {
return ( return (
<div> <div>
<h1>Upgrade</h1> <h1>Upgrade</h1>
<Image src="/test.jpg" width="200" height="300" />
<Image <Image
src="/test.jpg" src="/test.jpg"
width="200" width="100"
height="300" height="200"
style={{
maxWidth: "100%",
height: "auto"
}} />
<Image
src="/test.jpg"
width="300"
height="400"
style={{ style={{
maxWidth: "100%", maxWidth: "100%",
height: "auto" height: "auto"
......
...@@ -34,7 +34,7 @@ function findAndReplaceProps( ...@@ -34,7 +34,7 @@ function findAndReplaceProps(
el.value.openingElement.name.name === tagName el.value.openingElement.name.name === tagName
) )
.forEach((el) => { .forEach((el) => {
let layout = 'intrisic' let layout = 'intrinsic'
let objectFit = null let objectFit = null
let objectPosition = null let objectPosition = null
let styleExpProps = [] let styleExpProps = []
...@@ -43,21 +43,20 @@ function findAndReplaceProps( ...@@ -43,21 +43,20 @@ function findAndReplaceProps(
if (a.type !== 'JSXAttribute') { if (a.type !== 'JSXAttribute') {
return true return true
} }
// TODO: hanlde case when not Literal
if (a.value?.type === 'Literal') { if (a.name.name === 'layout' && 'value' in a.value) {
if (a.name.name === 'layout') { layout = String(a.value.value)
layout = String(a.value.value) return false
return false
}
if (a.name.name === 'objectFit') {
objectFit = String(a.value.value)
return false
}
if (a.name.name === 'objectPosition') {
objectPosition = String(a.value.value)
return false
}
} }
if (a.name.name === 'objectFit' && 'value' in a.value) {
objectFit = String(a.value.value)
return false
}
if (a.name.name === 'objectPosition' && 'value' in a.value) {
objectPosition = String(a.value.value)
return false
}
if (a.name.name === 'style') { if (a.name.name === 'style') {
if ( if (
a.value?.type === 'JSXExpressionContainer' && a.value?.type === 'JSXExpressionContainer' &&
......
...@@ -306,7 +306,7 @@ function handleLoading( ...@@ -306,7 +306,7 @@ function handleLoading(
img.getBoundingClientRect().width / window.innerWidth img.getBoundingClientRect().width / window.innerWidth
if (widthViewportRatio < 0.6) { if (widthViewportRatio < 0.6) {
warnOnce( warnOnce(
`Image with src "${src}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/future/image#sizes` `Image with src "${src}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/image#sizes`
) )
} }
} }
......
...@@ -864,7 +864,7 @@ export default function Image({ ...@@ -864,7 +864,7 @@ export default function Image({
// https://web.dev/lcp/#measure-lcp-in-javascript // https://web.dev/lcp/#measure-lcp-in-javascript
warnOnce( 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.` + `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` `\nRead more: https://nextjs.org/docs/api-reference/next/legacy/image#priority`
) )
} }
} }
......
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