Unverified Commit c8bc17f3 authored by Alex Castle's avatar Alex Castle Committed by GitHub

Support for custom image loaders via image component prop (#20216)

This is a #19325 reconfigured to support a loader passed in via a `loader` prop on the Image component, rather than using a config-based approach.

The idea is that applications wanting to use a custom loader will create a wrapper element for the  image component that incorporates that loader. See a simple example of this pattern in the integration tests. 

This solution is similar to the one prototyped by @ricokahler in #20213 and described at https://github.com/vercel/next.js/issues/18606#issuecomment-720149156

---

Closes #19325
Fixes #18606
parent b6c6770c
...@@ -16,7 +16,20 @@ if (typeof window === 'undefined') { ...@@ -16,7 +16,20 @@ if (typeof window === 'undefined') {
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number] type LoadingValue = typeof VALID_LOADING_VALUES[number]
const loaders = new Map<LoaderValue, (props: LoaderProps) => string>([ export type ImageLoader = (resolverProps: ImageLoaderProps) => string
export type ImageLoaderProps = {
src: string
width: number
quality?: number
}
type DefaultImageLoaderProps = ImageLoaderProps & { root: string }
const loaders = new Map<
LoaderValue,
(props: DefaultImageLoaderProps) => string
>([
['imgix', imgixLoader], ['imgix', imgixLoader],
['cloudinary', cloudinaryLoader], ['cloudinary', cloudinaryLoader],
['akamai', akamaiLoader], ['akamai', akamaiLoader],
...@@ -39,6 +52,7 @@ export type ImageProps = Omit< ...@@ -39,6 +52,7 @@ export type ImageProps = Omit<
'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading' | 'style' 'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading' | 'style'
> & { > & {
src: string src: string
loader?: ImageLoader
quality?: number | string quality?: number | string
priority?: boolean priority?: boolean
loading?: LoadingValue loading?: LoadingValue
...@@ -103,28 +117,11 @@ function getWidths( ...@@ -103,28 +117,11 @@ function getWidths(
return { widths, kind: 'x' } return { widths, kind: 'x' }
} }
type CallLoaderProps = {
src: string
width: number
quality?: number
}
function callLoader(loaderProps: CallLoaderProps): string {
const load = loaders.get(configLoader)
if (load) {
return load({ root: configPath, ...loaderProps })
}
throw new Error(
`Unknown "loader" found in "next.config.js". Expected: ${VALID_LOADERS.join(
', '
)}. Received: ${configLoader}`
)
}
type GenImgAttrsData = { type GenImgAttrsData = {
src: string src: string
unoptimized: boolean unoptimized: boolean
layout: LayoutValue layout: LayoutValue
loader: ImageLoader
width?: number width?: number
quality?: number quality?: number
sizes?: string sizes?: string
...@@ -143,6 +140,7 @@ function generateImgAttrs({ ...@@ -143,6 +140,7 @@ function generateImgAttrs({
width, width,
quality, quality,
sizes, sizes,
loader,
}: GenImgAttrsData): GenImgAttrsResult { }: GenImgAttrsData): GenImgAttrsResult {
if (unoptimized) { if (unoptimized) {
return { src, srcSet: undefined, sizes: undefined } return { src, srcSet: undefined, sizes: undefined }
...@@ -151,22 +149,18 @@ function generateImgAttrs({ ...@@ -151,22 +149,18 @@ function generateImgAttrs({
const { widths, kind } = getWidths(width, layout) const { widths, kind } = getWidths(width, layout)
const last = widths.length - 1 const last = widths.length - 1
const srcSet = widths return {
.map( src: loader({ src, quality, width: widths[last] }),
(w, i) => sizes: !sizes && kind === 'w' ? '100vw' : sizes,
`${callLoader({ src, quality, width: w })} ${ srcSet: widths
kind === 'w' ? w : i + 1 .map(
}${kind}` (w, i) =>
) `${loader({ src, quality, width: w })} ${
.join(', ') kind === 'w' ? w : i + 1
}${kind}`
if (!sizes && kind === 'w') { )
sizes = '100vw' .join(', '),
} }
src = callLoader({ src, quality, width: widths[last] })
return { src, sizes, srcSet }
} }
function getInt(x: unknown): number | undefined { function getInt(x: unknown): number | undefined {
...@@ -179,6 +173,18 @@ function getInt(x: unknown): number | undefined { ...@@ -179,6 +173,18 @@ function getInt(x: unknown): number | undefined {
return undefined return undefined
} }
function defaultImageLoader(loaderProps: ImageLoaderProps) {
const load = loaders.get(configLoader)
if (load) {
return load({ root: configPath, ...loaderProps })
}
throw new Error(
`Unknown "loader" found in "next.config.js". Expected: ${VALID_LOADERS.join(
', '
)}. Received: ${configLoader}`
)
}
export default function Image({ export default function Image({
src, src,
sizes, sizes,
...@@ -191,6 +197,7 @@ export default function Image({ ...@@ -191,6 +197,7 @@ export default function Image({
height, height,
objectFit, objectFit,
objectPosition, objectPosition,
loader = defaultImageLoader,
...all ...all
}: ImageProps) { }: ImageProps) {
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
...@@ -377,6 +384,7 @@ export default function Image({ ...@@ -377,6 +384,7 @@ export default function Image({
width: widthInt, width: widthInt,
quality: qualityInt, quality: qualityInt,
sizes, sizes,
loader,
}) })
} }
...@@ -444,13 +452,16 @@ export default function Image({ ...@@ -444,13 +452,16 @@ export default function Image({
//BUILT IN LOADERS //BUILT IN LOADERS
type LoaderProps = CallLoaderProps & { root: string }
function normalizeSrc(src: string): string { function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src return src[0] === '/' ? src.slice(1) : src
} }
function imgixLoader({ root, src, width, quality }: LoaderProps): string { function imgixLoader({
root,
src,
width,
quality,
}: DefaultImageLoaderProps): string {
// Demo: https://static.imgix.net/daisy.png?format=auto&fit=max&w=300 // Demo: https://static.imgix.net/daisy.png?format=auto&fit=max&w=300
const params = ['auto=format', 'fit=max', 'w=' + width] const params = ['auto=format', 'fit=max', 'w=' + width]
let paramsString = '' let paramsString = ''
...@@ -464,18 +475,28 @@ function imgixLoader({ root, src, width, quality }: LoaderProps): string { ...@@ -464,18 +475,28 @@ function imgixLoader({ root, src, width, quality }: LoaderProps): string {
return `${root}${normalizeSrc(src)}${paramsString}` return `${root}${normalizeSrc(src)}${paramsString}`
} }
function akamaiLoader({ root, src, width }: LoaderProps): string { function akamaiLoader({ root, src, width }: DefaultImageLoaderProps): string {
return `${root}${normalizeSrc(src)}?imwidth=${width}` return `${root}${normalizeSrc(src)}?imwidth=${width}`
} }
function cloudinaryLoader({ root, src, width, quality }: LoaderProps): string { function cloudinaryLoader({
root,
src,
width,
quality,
}: DefaultImageLoaderProps): string {
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg // Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')] const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
let paramsString = params.join(',') + '/' let paramsString = params.join(',') + '/'
return `${root}${paramsString}${normalizeSrc(src)}` return `${root}${paramsString}${normalizeSrc(src)}`
} }
function defaultLoader({ root, src, width, quality }: LoaderProps): string { function defaultLoader({
root,
src,
width,
quality,
}: DefaultImageLoaderProps): string {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const missingValues = [] const missingValues = []
......
module.exports = {
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
path: 'https://globalresolver.com/myaccount/',
loader: 'imgix',
},
}
import React from 'react'
import Image from 'next/image'
const myLoader = ({ src, width, quality }) => {
return `https://customresolver.com/${src}?w~~${width},q~~${quality}`
}
const MyImage = (props) => {
return <Image loader={myLoader} {...props}></Image>
}
const Page = () => {
return (
<div>
<p>Image Client Side Test</p>
<MyImage
id="basic-image"
src="foo.jpg"
loading="eager"
width={300}
height={400}
quality={60}
/>
<Image
id="unoptimized-image"
unoptimized
src="https://arbitraryurl.com/foo.jpg"
loading="eager"
width={300}
height={400}
/>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
const myLoader = ({ src, width, quality }) => {
return `https://customresolver.com/${src}?w~~${width},q~~${quality}`
}
const MyImage = (props) => {
return <Image loader={myLoader} {...props}></Image>
}
const Page = () => {
return (
<div>
<p>Image SSR Test</p>
<MyImage
id="basic-image"
src="foo.jpg"
loading="eager"
width={300}
height={400}
quality={60}
/>
<Image
id="unoptimized-image"
unoptimized
src="https://arbitraryurl.com/foo.jpg"
loading="eager"
width={300}
height={400}
/>
<Link href="/client-side">
<a id="clientlink">Client Side</a>
</Link>
</div>
)
}
export default Page
/* eslint-env jest */
import { join } from 'path'
import { killApp, findPort, nextStart, nextBuild } from 'next-test-utils'
import webdriver from 'next-webdriver'
jest.setTimeout(1000 * 30)
const appDir = join(__dirname, '../')
let appPort
let app
let browser
function runTests() {
it('Should use a custom resolver for image URL', async () => {
expect(await browser.elementById('basic-image').getAttribute('src')).toBe(
'https://customresolver.com/foo.jpg?w~~1024,q~~60'
)
})
it('should add a srcset based on the custom resolver', async () => {
expect(
await browser.elementById('basic-image').getAttribute('srcset')
).toBe(
'https://customresolver.com/foo.jpg?w~~480,q~~60 1x, https://customresolver.com/foo.jpg?w~~1024,q~~60 2x'
)
})
it('should support the unoptimized attribute', async () => {
expect(
await browser.elementById('unoptimized-image').getAttribute('src')
).toBe('https://arbitraryurl.com/foo.jpg')
})
}
describe('Custom Resolver Tests', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
describe('SSR Custom Loader Tests', () => {
beforeAll(async () => {
browser = await webdriver(appPort, '/')
})
afterAll(async () => {
browser = null
})
runTests()
})
describe('Client-side Custom Loader Tests', () => {
beforeAll(async () => {
browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('#clientlink').click()
})
afterAll(async () => {
browser = null
})
runTests()
})
})
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