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

Add codemods for `next/image` (#41004)

This adds two codemods for `next/image`.

The first codemod a safe solution to upgrade from 12 to 13 by swapping
to `next/legacy/image`.

The second codemod is an experimental solution that attempts to automate
the [migration
guide](https://nextjs.org/docs/api-reference/next/future/image#migration).
parent 09d642a7
......@@ -17,6 +17,55 @@ Codemods are transformations that run on your codebase programmatically. This al
- `--dry` Do a dry-run, no code will be edited
- `--print` Prints the changed output for comparison
## Next.js 13
### `next-image-to-legacy-image`
Safely migrates existing Next.js 10, 11, 12 applications importing `next/image` to the renamed `next/legacy/image` import in Next.js 13.
For example:
```jsx
import Image1 from 'next/image'
import Image2 from 'next/future/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}
```
Transforms into:
```jsx
import Image1 from 'next/legacy/image'
import Image2 from 'next/image'
export default function Home() {
return (
<div>
<Image1 src="/test.jpg" width="200" height="300" />
<Image2 src="/test.png" width="500" height="400" />
</div>
)
}
```
### `next-image-experimental` (experimental)
Dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props.
- Removes `layout` prop and adds `style`
- Removes `objectFit` prop and adds `style`
- Removes `objectPosition` prop and adds `style`
- Removes `lazyBoundary` prop
- Removes `lazyRoot` prop
- TODO: handle `loader`
## Next.js 11
### `cra-to-next` (experimental)
......
......@@ -4,6 +4,11 @@ description: Learn how to upgrade Next.js.
# Upgrade Guide
## Upgrading from 12 to 13
The `next/image` import was renamed to `next/legacy/image`. The `next/future/image` import was renamed to `next/image`.
A [codemod is available](/docs/advanced-features/codemods.md#next-image-to-legacy-image) to safely and automatically rename your imports.
## Upgrading to 12.2
If you were using Middleware prior to `12.2`, please see the [upgrade guide](https://nextjs.org/docs/messages/middleware-upgrade-guide) for more information.
......
import Image from "next/legacy/image";
import Named, { Blarg } from "next/legacy/image";
import Foo from "foo";
import img from "../public/img.jpg";
export default function Home() {
const myStyle = { color: 'black' };
return (
<div>
<h1>Upgrade</h1>
<Image src="/test.jpg" width="200" height="300" />
<Image src="/test.jpg" width="200" height="300" layout="intrinsic" />
<Image src="/test.jpg" width="200" height="300" layout="responsive" />
<Image src="/test.jpg" width="200" height="300" layout="fixed" />
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
alt="example alt text"
src={img}
layout="fill"
objectFit="contain"
/>
</div>
<Named src="/test.png" width="500" height="400" layout="fixed" />
<Foo bar="1" />
<Image src="/test.jpg" width="200" height="300" layout="responsive" style={{color: "green"}} />
<Image src="/test.jpg" width="200" height="300" layout="responsive" style={{color: myStyle.color}} />
<Image src="/test.jpg" width="200" height="300" layout="responsive" sizes="50vw" style={{color: "#fff"}} />
<Image src="/test.jpg" width="200" height="300" layout="fixed" lazyBoundary="1500px" lazyRoot={img} />
<Image src="/test.lit" width="200" height="300" layout="responsive" style={myStyle} />
<Image src="/test.dot" width="200" height="300" layout="responsive" style={{...myStyle}} />
</div>
);
}
\ No newline at end of file
import Image from "next/image";
import Named, { Blarg } from "next/image";
import Foo from "foo";
import img from "../public/img.jpg";
export default function Home() {
const myStyle = { color: 'black' };
return (
<div>
<h1>Upgrade</h1>
<Image src="/test.jpg" width="200" height="300" />
<Image
src="/test.jpg"
width="200"
height="300"
style={{
maxWidth: "100%",
height: "auto"
}} />
<Image
src="/test.jpg"
width="200"
height="300"
sizes="100vw"
style={{
width: "100%",
height: "auto"
}} />
<Image src="/test.jpg" width="200" height="300" />
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
alt="example alt text"
src={img}
fill
sizes="100vw"
style={{
objectFit: "contain"
}} />
</div>
<Named src="/test.png" width="500" height="400" />
<Foo bar="1" />
<Image
src="/test.jpg"
width="200"
height="300"
sizes="100vw"
style={{
color: "green",
width: "100%",
height: "auto"
}} />
<Image
src="/test.jpg"
width="200"
height="300"
sizes="100vw"
style={{
color: myStyle.color,
width: "100%",
height: "auto"
}} />
<Image
src="/test.jpg"
width="200"
height="300"
sizes="50vw"
style={{
color: "#fff",
width: "100%",
height: "auto"
}} />
<Image src="/test.jpg" width="200" height="300" />
<Image
src="/test.lit"
width="200"
height="300"
sizes="100vw"
style={{
...myStyle,
width: "100%",
height: "auto"
}} />
<Image
src="/test.dot"
width="200"
height="300"
sizes="100vw"
style={{
...myStyle,
width: "100%",
height: "auto"
}} />
</div>
);
}
\ No newline at end of file
export async function Home() {
const Image = await import("next/image");
const Named = await import("next/image");
const Foo = await import("foo");
const Future1 = await import("next/future/image");
const Future2 = await import("next/future/image");
return (<div>
<h1>Both</h1>
<Image src="/test.jpg" width="200" height="300" />
<Named src="/test.png" width="500" height="400" />
<Future1 src="/test.webp" width="60" height="70" />
<Future2 src="/test.avif" width="80" height="90" />
</div>)
}
\ No newline at end of file
export async function Home() {
const Image = await import("next/legacy/image");
const Named = await import("next/legacy/image");
const Foo = await import("foo");
const Future1 = await import("next/image");
const Future2 = await import("next/image");
return (<div>
<h1>Both</h1>
<Image src="/test.jpg" width="200" height="300" />
<Named src="/test.png" width="500" height="400" />
<Future1 src="/test.webp" width="60" height="70" />
<Future2 src="/test.avif" width="80" height="90" />
</div>)
}
\ No newline at end of file
import Image from "next/image";
import Named from "next/image";
import Foo from "foo";
import Future1 from "next/future/image";
import Future2 from "next/future/image";
export default function Home() {
return (<div>
<h1>Both</h1>
<Image src="/test.jpg" width="200" height="300" />
<Named src="/test.png" width="500" height="400" />
<Future1 src="/test.webp" width="60" height="70" />
<Future2 src="/test.avif" width="80" height="90" />
</div>)
}
\ No newline at end of file
import Image from "next/legacy/image";
import Named from "next/legacy/image";
import Foo from "foo";
import Future1 from "next/image";
import Future2 from "next/image";
export default function Home() {
return (<div>
<h1>Both</h1>
<Image src="/test.jpg" width="200" height="300" />
<Named src="/test.png" width="500" height="400" />
<Future1 src="/test.webp" width="60" height="70" />
<Future2 src="/test.avif" width="80" height="90" />
</div>)
}
\ No newline at end of file
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const { readdirSync } = require('fs')
const { join } = require('path')
const fixtureDir = 'next-image-experimental'
const fixtureDirPath = join(__dirname, '..', '__testfixtures__', fixtureDir)
const fixtures = readdirSync(fixtureDirPath)
.filter(file => file.endsWith('.input.js'))
.map(file => file.replace('.input.js', ''))
for (const fixture of fixtures) {
const prefix = `${fixtureDir}/${fixture}`;
defineTest(__dirname, fixtureDir, null, prefix)
}
/* global jest */
jest.autoMockOff()
const defineTest = require('jscodeshift/dist/testUtils').defineTest
const { readdirSync } = require('fs')
const { join } = require('path')
const fixtureDir = 'next-image-to-legacy-image'
const fixtureDirPath = join(__dirname, '..', '__testfixtures__', fixtureDir)
const fixtures = readdirSync(fixtureDirPath)
.filter(file => file.endsWith('.input.js'))
.map(file => file.replace('.input.js', ''))
for (const fixture of fixtures) {
const prefix = `${fixtureDir}/${fixture}`;
defineTest(__dirname, fixtureDir, null, prefix)
}
import type {
API,
FileInfo,
ImportDefaultSpecifier,
JSXAttribute,
Options,
} from 'jscodeshift'
export default function transformer(
file: FileInfo,
api: API,
options: Options
) {
const j = api.jscodeshift
const root = j(file.source)
// Before: import Image from "next/legacy/image"
// After: import Image from "next/image"
root
.find(j.ImportDeclaration, {
source: { value: 'next/legacy/image' },
})
.forEach((imageImport) => {
const defaultSpecifier = imageImport.node.specifiers?.find(
(node) => node.type === 'ImportDefaultSpecifier'
) as ImportDefaultSpecifier | undefined
const defaultSpecifierName = defaultSpecifier?.local?.name
j(imageImport).replaceWith(
j.importDeclaration(
imageImport.node.specifiers,
j.stringLiteral('next/image')
)
)
const layoutToStyle: Record<string, Record<string, string> | null> = {
intrinsic: { maxWidth: '100%', height: 'auto' },
responsive: { width: '100%', height: 'auto' },
fill: null,
fixed: null,
}
const layoutToSizes: Record<string, string | null> = {
intrinsic: null,
responsive: '100vw',
fill: '100vw',
fixed: null,
}
root
.find(j.JSXElement)
.filter(
(el) =>
el.value.openingElement.name &&
el.value.openingElement.name.type === 'JSXIdentifier' &&
el.value.openingElement.name.name === defaultSpecifierName
)
.forEach((el) => {
let layout = 'intrisic'
let objectFit = null
let objectPosition = null
let styleExpProps = []
let sizesAttr: JSXAttribute | null = null
const attributes = el.node.openingElement.attributes?.filter((a) => {
if (a.type !== 'JSXAttribute') {
return true
}
// TODO: hanlde case when not Literal
if (a.value?.type === 'Literal') {
if (a.name.name === 'layout') {
layout = String(a.value.value)
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 === 'style') {
if (
a.value?.type === 'JSXExpressionContainer' &&
a.value.expression.type === 'ObjectExpression'
) {
styleExpProps = a.value.expression.properties
} else if (
a.value?.type === 'JSXExpressionContainer' &&
a.value.expression.type === 'Identifier'
) {
styleExpProps = [
j.spreadElement(j.identifier(a.value.expression.name)),
]
} else {
console.warn('Unknown style attribute value detected', a.value)
}
return false
}
if (a.name.name === 'sizes') {
sizesAttr = a
return false
}
if (a.name.name === 'lazyBoundary') {
return false
}
if (a.name.name === 'lazyRoot') {
return false
}
return true
})
if (layout === 'fill') {
attributes.push(j.jsxAttribute(j.jsxIdentifier('fill')))
}
const sizes = layoutToSizes[layout]
if (sizes && !sizesAttr) {
sizesAttr = j.jsxAttribute(
j.jsxIdentifier('sizes'),
j.literal(sizes)
)
}
if (sizesAttr) {
attributes.push(sizesAttr)
}
let style = layoutToStyle[layout]
if (style || objectFit || objectPosition) {
if (!style) {
style = {}
}
if (objectFit) {
style.objectFit = objectFit
}
if (objectPosition) {
style.objectPosition = objectPosition
}
Object.entries(style).forEach(([key, value]) => {
styleExpProps.push(
j.objectProperty(j.identifier(key), j.stringLiteral(value))
)
})
const styleAttribute = j.jsxAttribute(
j.jsxIdentifier('style'),
j.jsxExpressionContainer(j.objectExpression(styleExpProps))
)
attributes.push(styleAttribute)
}
// TODO: should we add `alt=""` attribute?
// We should probably let the use it manually.
j(el).replaceWith(
j.jsxElement(
j.jsxOpeningElement(
el.node.openingElement.name,
attributes,
el.node.openingElement.selfClosing
),
el.node.closingElement,
el.node.children
)
)
})
})
// Before: const Image = await import("next/legacy/image")
// After: const Image = await import("next/image")
root
.find(j.ImportExpression, {
source: { value: 'next/legacy/image' },
})
.forEach((imageImport) => {
j(imageImport).replaceWith(
j.importExpression(j.stringLiteral('next/image'))
)
})
// TODO: do the same transforms for dynamic imports
return root.toSource(options)
}
import type { API, FileInfo, Options } from 'jscodeshift'
export default function transformer(
file: FileInfo,
api: API,
options: Options
) {
const j = api.jscodeshift
const root = j(file.source)
// Before: import Image from "next/image"
// After: import Image from "next/legacy/image"
root
.find(j.ImportDeclaration, {
source: { value: 'next/image' },
})
.forEach((imageImport) => {
j(imageImport).replaceWith(
j.importDeclaration(
imageImport.node.specifiers,
j.stringLiteral('next/legacy/image')
)
)
})
// Before: const Image = await import("next/image")
// After: const Image = await import("next/legacy/image")
root
.find(j.ImportExpression, {
source: { value: 'next/image' },
})
.forEach((imageImport) => {
j(imageImport).replaceWith(
j.importExpression(j.stringLiteral('next/legacy/image'))
)
})
// Before: import Image from "next/future/image"
// After: import Image from "next/image"
root
.find(j.ImportDeclaration, {
source: { value: 'next/future/image' },
})
.forEach((imageFutureImport) => {
j(imageFutureImport).replaceWith(
j.importDeclaration(
imageFutureImport.node.specifiers,
j.stringLiteral('next/image')
)
)
})
// Before: const Image = await import("next/future/image")
// After: const Image = await import("next/image")
root
.find(j.ImportExpression, {
source: { value: 'next/future/image' },
})
.forEach((imageFutureImport) => {
j(imageFutureImport).replaceWith(
j.importExpression(j.stringLiteral('next/image'))
)
})
// Learn more about renaming an import declaration here:
// https://www.codeshiftcommunity.com/docs/import-manipulation/#replacerename-an-import-declaration
return root.toSource(options)
}
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