Unverified Commit 1a8ad140 authored by Steven's avatar Steven Committed by GitHub

Rename next/image `dangerously-unoptimized` to `custom` and warn when applicable (#26998)

Since we are no longer accepting new built-in loaders, users may wish to use a different cloud provider.

So this PR renames `dangerously-unoptimized` to `custom` to handle this case as well as the intention of `next export`.

If the user doesn't add a `loader` prop, we throw an error.
If the user adds a `loader` prop but it doesn't return the width, we print a warning.

- Follow up to #26847 
- Fixes #21079 
- Fixes #19612 
- Related to #26850 
parent 1c2b1713
...@@ -121,7 +121,7 @@ The following Image Optimization cloud providers are included: ...@@ -121,7 +121,7 @@ The following Image Optimization cloud providers are included:
- [Imgix](https://www.imgix.com): `loader: 'imgix'` - [Imgix](https://www.imgix.com): `loader: 'imgix'`
- [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'` - [Cloudinary](https://cloudinary.com): `loader: 'cloudinary'`
- [Akamai](https://www.akamai.com): `loader: 'akamai'` - [Akamai](https://www.akamai.com): `loader: 'akamai'`
- dangerously-unoptimized: uses image directly from `src` prop without optimization (only needed with `next export` or when the built-in `_next/image` optimizer can not be leveraged) `loader: 'dangerously-unoptimized'` - Custom: `loader: 'custom'` use a custom cloud provider by implementing the [`loader`](/docs/api-reference/next/image.md#loader) prop on the `next/image` component
- Default: Works automatically with `next dev`, `next start`, or a custom server - Default: Works automatically with `next dev`, `next start`, or a custom server
If you need a different provider, you can use the [`loader`](/docs/api-reference/next/image.md#loader) prop with `next/image`. If you need a different provider, you can use the [`loader`](/docs/api-reference/next/image.md#loader) prop with `next/image`.
......
...@@ -249,6 +249,14 @@ ...@@ -249,6 +249,14 @@
"title": "next-head-count-missing", "title": "next-head-count-missing",
"path": "/errors/next-head-count-missing.md" "path": "/errors/next-head-count-missing.md"
}, },
{
"title": "next-image-missing-loader",
"path": "/errors/next-image-missing-loader.md"
},
{
"title": "next-image-missing-loader-width",
"path": "/errors/next-image-missing-loader-width.md"
},
{ {
"title": "next-image-unconfigured-host", "title": "next-image-unconfigured-host",
"path": "/errors/next-image-unconfigured-host.md" "path": "/errors/next-image-unconfigured-host.md"
......
# Missing `width` in the URL Returned by the Loader Prop on `next/image`
#### Why This Error Occurred
The [`loader`](https://nextjs.org/docs/api-reference/next/image#loader) prop on the `next/image` component allows you to override the built-in URL resolution with a custom implementation in order to support any 3rd party cloud provider that can perform Image Optimization.
This error occurred because the provided `loader()` function did not use `width` in the returned URL string. This means that the image will likely not be resized and therefore degrade performance.
#### Possible Ways to Fix It
- Ensure your Image Optimization provider can resize images. Then use the `width` parameter from the [`loader()`](https://nextjs.org/docs/api-reference/next/image#loader) function to construct the correct URL string.
- Add the [`unoptimized`](https://nextjs.org/docs/api-reference/next/image#unoptimized) prop.
### Useful Links
- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
# Missing `loader` Prop on `next/image`
#### Why This Error Occurred
When using the `next/image` component with [`loader="custom"`](https://nextjs.org/docs/basic-features/image-optimization#loader) in `next.config.js`, you must provide the [`loader`](https://nextjs.org/docs/api-reference/next/image#loader) prop to the component with your custom implementation.
#### Possible Ways to Fix It
- Add the [`loader`](https://nextjs.org/docs/api-reference/next/image#loader) prop to all usages of the `next/image` component.
- Change the [`loader`](https://nextjs.org/docs/basic-features/image-optimization#loader) configuration in `next.config.js`.
### Useful Links
- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
...@@ -32,11 +32,11 @@ const loaders = new Map< ...@@ -32,11 +32,11 @@ const loaders = new Map<
LoaderValue, LoaderValue,
(props: DefaultImageLoaderProps) => string (props: DefaultImageLoaderProps) => string
>([ >([
['default', defaultLoader],
['imgix', imgixLoader], ['imgix', imgixLoader],
['cloudinary', cloudinaryLoader], ['cloudinary', cloudinaryLoader],
['akamai', akamaiLoader], ['akamai', akamaiLoader],
['default', defaultLoader], ['custom', customLoader],
['dangerously-unoptimized', unoptimizedLoader],
]) ])
const VALID_LAYOUT_VALUES = [ const VALID_LAYOUT_VALUES = [
...@@ -338,6 +338,17 @@ export default function Image({ ...@@ -338,6 +338,17 @@ export default function Image({
const heightInt = getInt(height) const heightInt = getInt(height)
const qualityInt = getInt(quality) const qualityInt = getInt(quality)
let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:')) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = true
isLazy = false
}
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) {
isLazy = false
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( throw new Error(
...@@ -404,16 +415,16 @@ export default function Image({ ...@@ -404,16 +415,16 @@ export default function Image({
`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.` `Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`
) )
} }
} const rand = Math.floor(Math.random() * 1000) + 100
let isLazy = if (
!priority && (loading === 'lazy' || typeof loading === 'undefined') !unoptimized &&
if (src && src.startsWith('data:')) { !loader({ src, width: rand, quality: 75 }).includes(rand.toString())
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs ) {
unoptimized = true console.warn(
isLazy = false `Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` +
} `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`
if (src && typeof window !== 'undefined' && loadedImageURLs.has(src)) { )
isLazy = false }
} }
const [setRef, isIntersected] = useIntersection<HTMLImageElement>({ const [setRef, isIntersected] = useIntersection<HTMLImageElement>({
...@@ -626,8 +637,6 @@ export default function Image({ ...@@ -626,8 +637,6 @@ export default function Image({
) )
} }
//BUILT IN LOADERS
function normalizeSrc(src: string): string { function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src return src[0] === '/' ? src.slice(1) : src
} }
...@@ -669,8 +678,11 @@ function cloudinaryLoader({ ...@@ -669,8 +678,11 @@ function cloudinaryLoader({
return `${root}${paramsString}${normalizeSrc(src)}` return `${root}${paramsString}${normalizeSrc(src)}`
} }
function unoptimizedLoader({ src }: DefaultImageLoaderProps): string { function customLoader({ src }: DefaultImageLoaderProps): string {
return src throw new Error(
`Image with src "${src}" is missing "loader" prop.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`
)
} }
function defaultLoader({ function defaultLoader({
......
...@@ -3,7 +3,7 @@ export const VALID_LOADERS = [ ...@@ -3,7 +3,7 @@ export const VALID_LOADERS = [
'imgix', 'imgix',
'cloudinary', 'cloudinary',
'akamai', 'akamai',
'dangerously-unoptimized', 'custom',
] as const ] as const
export type LoaderValue = typeof VALID_LOADERS[number] export type LoaderValue = typeof VALID_LOADERS[number]
......
import Image from 'next/image' import Image from 'next/image'
const loader = undefined
export default () => ( export default () => (
<div> <div>
<p>Should succeed during export</p> <p>Should succeed during export</p>
<Image alt="icon" src="/i.png" width="10" height="10" /> <Image alt="icon" src="/i.png" width="10" height="10" loader={loader} />
</div> </div>
) )
...@@ -9,6 +9,7 @@ jest.setTimeout(1000 * 60 * 5) ...@@ -9,6 +9,7 @@ jest.setTimeout(1000 * 60 * 5)
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out') const outdir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js')) const nextConfig = new File(join(appDir, 'next.config.js'))
const pagesIndexJs = new File(join(appDir, 'pages', 'index.js'))
describe('Export with cloudinary loader next/image component', () => { describe('Export with cloudinary loader next/image component', () => {
beforeAll(async () => { beforeAll(async () => {
...@@ -44,16 +45,20 @@ describe('Export with cloudinary loader next/image component', () => { ...@@ -44,16 +45,20 @@ describe('Export with cloudinary loader next/image component', () => {
}) })
}) })
describe('Export with dangerously-unoptimized loader next/image component', () => { describe('Export with custom loader next/image component', () => {
beforeAll(async () => { beforeAll(async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
images: { images: {
loader: 'dangerously-unoptimized', loader: 'custom',
}, },
}) })
) )
await pagesIndexJs.replace(
'loader = undefined',
'loader = ({src}) => "/custom" + src'
)
}) })
it('should build successfully', async () => { it('should build successfully', async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
...@@ -69,10 +74,11 @@ describe('Export with dangerously-unoptimized loader next/image component', () = ...@@ -69,10 +74,11 @@ describe('Export with dangerously-unoptimized loader next/image component', () =
it('should contain img element with same src in html output', async () => { it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html')) const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('img[alt="icon"]').attr('src')).toBe('/i.png') expect($('img[alt="icon"]').attr('src')).toBe('/custom/i.png')
}) })
afterAll(async () => { afterAll(async () => {
await nextConfig.restore() await nextConfig.restore()
await pagesIndexJs.restore()
}) })
}) })
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
launchApp, launchApp,
nextBuild, nextBuild,
nextStart, nextStart,
renderViaHTTP,
waitFor, waitFor,
} from 'next-test-utils' } from 'next-test-utils'
import isAnimated from 'next/dist/compiled/is-animated' import isAnimated from 'next/dist/compiled/is-animated'
...@@ -730,7 +731,34 @@ describe('Image Optimizer', () => { ...@@ -730,7 +731,34 @@ describe('Image Optimizer', () => {
await nextConfig.restore() await nextConfig.restore()
expect(stderr).toContain( expect(stderr).toContain(
'Specified images.loader should be one of (default, imgix, cloudinary, akamai, dangerously-unoptimized), received invalid value (notreal)' 'Specified images.loader should be one of (default, imgix, cloudinary, akamai, custom), received invalid value (notreal)'
)
})
it('should error when loader=custom but loader prop is undefined', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
},
})
)
let output = ''
const appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
output += msg || ''
},
onStdout(msg) {
output += msg || ''
},
})
await renderViaHTTP(appPort, '/', {})
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(output).toMatch(
/Error: Image with src "(.+)" is missing "loader" prop/
) )
}) })
}) })
......
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