Unverified Commit 3a169fbb authored by Steven's avatar Steven Committed by GitHub

Separate config into `deviceSizes` and `iconSizes` (#18267)

This separates the `next.config.js` property `images.sizes` into to properties: `images.deviceSizes` and `images.iconSizes`.

The purpose is for images that are not intended to take up the majority of the viewport.


Related to #18122 
parent 557a0001
...@@ -50,14 +50,26 @@ export default Home ...@@ -50,14 +50,26 @@ export default Home
You can configure Image Optimization by using the `images` property in `next.config.js`. You can configure Image Optimization by using the `images` property in `next.config.js`.
### Sizes ### Device Sizes
You can specify a list of image widths to allow using the `sizes` property. Since images maintain their aspect ratio using the `width` and `height` attributes of the source image, there is no need to specify height in `next.config.js` – only the width. You can think of these as breakpoints. You can specify a list of device width breakpoints using the `deviceSizes` property. Since images maintain their aspect ratio using the `width` and `height` attributes of the source image, there is no need to specify height in `next.config.js` – only the width. These values will be used by the browser to determine which size image should load.
```js ```js
module.exports = { module.exports = {
images: { images: {
sizes: [320, 420, 768, 1024, 1200], deviceSizes: [320, 420, 768, 1024, 1200],
},
}
```
### Icon Sizes
You can specify a list of icon image widths using the `iconSizes` property. These widths should be smaller than the smallest value in `deviceSizes`. The purpose is for images that don't scale with the browser window, such as icons or badges. If `iconSizes` is not defined, then `deviceSizes` will be used.
```js
module.exports = {
images: {
iconSizes: [16, 32, 64],
}, },
} }
``` ```
...@@ -96,7 +108,6 @@ The following Image Optimization cloud providers are supported: ...@@ -96,7 +108,6 @@ The following Image Optimization cloud providers are supported:
- [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'`
## Related ## Related
For more information on what to do next, we recommend the following sections: For more information on what to do next, we recommend the following sections:
...@@ -107,4 +118,3 @@ For more information on what to do next, we recommend the following sections: ...@@ -107,4 +118,3 @@ For more information on what to do next, we recommend the following sections:
<small>See all available properties for the Image component</small> <small>See all available properties for the Image component</small>
</a> </a>
</div> </div>
...@@ -1110,11 +1110,15 @@ export default async function build( ...@@ -1110,11 +1110,15 @@ export default async function build(
) )
} }
const images = { ...config.images }
const { deviceSizes, iconSizes } = images
images.sizes = [...deviceSizes, ...iconSizes]
await promises.writeFile( await promises.writeFile(
path.join(distDir, IMAGES_MANIFEST), path.join(distDir, IMAGES_MANIFEST),
JSON.stringify({ JSON.stringify({
version: 1, version: 1,
images: config.images, images,
}), }),
'utf8' 'utf8'
) )
......
...@@ -991,7 +991,8 @@ export default async function getBaseWebpackConfig( ...@@ -991,7 +991,8 @@ export default async function getBaseWebpackConfig(
config.experimental.scrollRestoration config.experimental.scrollRestoration
), ),
'process.env.__NEXT_IMAGE_OPTS': JSON.stringify({ 'process.env.__NEXT_IMAGE_OPTS': JSON.stringify({
sizes: config.images.sizes, deviceSizes: config.images.deviceSizes,
iconSizes: config.images.iconSizes,
path: config.images.path, path: config.images.path,
loader: config.images.loader, loader: config.images.loader,
...(dev ...(dev
......
...@@ -14,7 +14,8 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([ ...@@ -14,7 +14,8 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([
type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default' type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default'
type ImageData = { type ImageData = {
sizes: number[] deviceSizes: number[]
iconSizes: number[]
loader: LoaderKey loader: LoaderKey
path: string path: string
domains?: string[] domains?: string[]
...@@ -36,12 +37,15 @@ type ImageProps = Omit< ...@@ -36,12 +37,15 @@ type ImageProps = Omit<
const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any
const { const {
sizes: configSizes, deviceSizes: configDeviceSizes,
iconSizes: configIconSizes,
loader: configLoader, loader: configLoader,
path: configPath, path: configPath,
domains: configDomains, domains: configDomains,
} = imageData } = imageData
configSizes.sort((a, b) => a - b) // smallest to largest // sort smallest to largest
configDeviceSizes.sort((a, b) => a - b)
configIconSizes.sort((a, b) => a - b)
let cachedObserver: IntersectionObserver let cachedObserver: IntersectionObserver
const IntersectionObserver = const IntersectionObserver =
...@@ -79,12 +83,16 @@ function getObserver(): IntersectionObserver | undefined { ...@@ -79,12 +83,16 @@ function getObserver(): IntersectionObserver | undefined {
)) ))
} }
function getWidthsFromConfig(width: number | undefined) { function getDeviceSizes(width: number | undefined): number[] {
if (typeof width !== 'number') { if (typeof width !== 'number') {
return configSizes return configDeviceSizes
}
const smallest = configDeviceSizes[0]
if (width < smallest && configIconSizes.includes(width)) {
return [width]
} }
const widths: number[] = [] const widths: number[] = []
for (let size of configSizes) { for (let size of configDeviceSizes) {
widths.push(size) widths.push(size)
if (size >= width) { if (size >= width) {
break break
...@@ -102,7 +110,7 @@ function computeSrc( ...@@ -102,7 +110,7 @@ function computeSrc(
if (unoptimized) { if (unoptimized) {
return src return src
} }
const widths = getWidthsFromConfig(width) const widths = getDeviceSizes(width)
const largest = widths[widths.length - 1] const largest = widths[widths.length - 1]
return callLoader({ src, width: largest, quality }) return callLoader({ src, width: largest, quality })
} }
...@@ -136,7 +144,8 @@ function generateSrcSet({ ...@@ -136,7 +144,8 @@ function generateSrcSet({
if (unoptimized) { if (unoptimized) {
return undefined return undefined
} }
return getWidthsFromConfig(width)
return getDeviceSizes(width)
.map((w) => `${callLoader({ src, width: w, quality })} ${w}w`) .map((w) => `${callLoader({ src, width: w, quality })} ${w}w`)
.join(', ') .join(', ')
} }
......
...@@ -24,7 +24,8 @@ const defaultConfig: { [key: string]: any } = { ...@@ -24,7 +24,8 @@ const defaultConfig: { [key: string]: any } = {
poweredByHeader: true, poweredByHeader: true,
compress: true, compress: true,
images: { images: {
sizes: [320, 420, 768, 1024, 1200], deviceSizes: [320, 420, 768, 1024, 1200],
iconSizes: [],
domains: [], domains: [],
path: '/_next/image', path: '/_next/image',
loader: 'default', loader: 'default',
...@@ -253,26 +254,53 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -253,26 +254,53 @@ function assignDefaults(userConfig: { [key: string]: any }) {
) )
} }
} }
if (images.sizes) { if (images.deviceSizes) {
if (!Array.isArray(images.sizes)) { const { deviceSizes } = images
if (!Array.isArray(deviceSizes)) {
throw new Error( throw new Error(
`Specified images.sizes should be an Array received ${typeof images.sizes}` `Specified images.deviceSizes should be an Array received ${typeof deviceSizes}`
) )
} }
if (images.sizes.length > 50) { if (deviceSizes.length > 25) {
throw new Error( throw new Error(
`Specified images.sizes exceeds length of 50, received length (${images.sizes.length}), please reduce the length of the array to continue` `Specified images.deviceSizes exceeds length of 25, received length (${deviceSizes.length}), please reduce the length of the array to continue`
) )
} }
const invalid = images.sizes.filter((d: unknown) => { const invalid = deviceSizes.filter((d: unknown) => {
return typeof d !== 'number' || d < 1 || d > 10000 return typeof d !== 'number' || d < 1 || d > 10000
}) })
if (invalid.length > 0) { if (invalid.length > 0) {
throw new Error( throw new Error(
`Specified images.sizes should be an Array of numbers that are between 1 and 10000, received invalid values (${invalid.join( `Specified images.deviceSizes should be an Array of numbers that are between 1 and 10000, received invalid values (${invalid.join(
', '
)})`
)
}
}
if (images.iconSizes) {
const { iconSizes } = images
if (!Array.isArray(iconSizes)) {
throw new Error(
`Specified images.iconSizes should be an Array received ${typeof iconSizes}`
)
}
if (iconSizes.length > 25) {
throw new Error(
`Specified images.iconSizes exceeds length of 25, received length (${iconSizes.length}), please reduce the length of the array to continue`
)
}
const invalid = iconSizes.filter((d: unknown) => {
return typeof d !== 'number' || d < 1 || d > 10000
})
if (invalid.length > 0) {
throw new Error(
`Specified images.iconSizes should be an Array of numbers that are between 1 and 10000, received invalid values (${invalid.join(
', ' ', '
)})` )})`
) )
......
...@@ -23,6 +23,14 @@ const CACHE_VERSION = 1 ...@@ -23,6 +23,14 @@ const CACHE_VERSION = 1
const ANIMATABLE_TYPES = [WEBP, PNG, GIF] const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
const VECTOR_TYPES = [SVG] const VECTOR_TYPES = [SVG]
type ImageData = {
deviceSizes: number[]
iconSizes: number[]
loader: string
path: string
domains?: string[]
}
export async function imageOptimizer( export async function imageOptimizer(
server: Server, server: Server,
req: IncomingMessage, req: IncomingMessage,
...@@ -30,7 +38,9 @@ export async function imageOptimizer( ...@@ -30,7 +38,9 @@ export async function imageOptimizer(
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
) { ) {
const { nextConfig, distDir } = server const { nextConfig, distDir } = server
const { sizes = [], domains = [], loader } = nextConfig?.images || {} const imageData: ImageData = nextConfig.images
const { deviceSizes = [], iconSizes = [], domains = [], loader } = imageData
const sizes = [...deviceSizes, ...iconSizes]
if (loader !== 'default') { if (loader !== 'default') {
await server.render404(req, res, parsedUrl) await server.render404(req, res, parsedUrl)
......
module.exports = { module.exports = {
images: { images: {
sizes: [480, 1024, 1600, 2000], deviceSizes: [480, 1024, 1600, 2000],
iconSizes: [16, 64],
path: 'https://example.com/myaccount/', path: 'https://example.com/myaccount/',
loader: 'imgix', loader: 'imgix',
}, },
......
...@@ -53,6 +53,20 @@ const ClientSide = () => { ...@@ -53,6 +53,20 @@ const ClientSide = () => {
width={300} width={300}
height={400} height={400}
/> />
<Image
id="icon-image-64"
src="/icon.png"
loading="eager"
width={64}
height={64}
/>
<Image
id="icon-image-16"
src="/icon.png"
loading="eager"
width={16}
height={16}
/>
<Link href="/errors"> <Link href="/errors">
<a id="errorslink">Errors</a> <a id="errorslink">Errors</a>
</Link> </Link>
......
...@@ -70,6 +70,20 @@ const Page = () => { ...@@ -70,6 +70,20 @@ const Page = () => {
width={300} width={300}
height={400} height={400}
/> />
<Image
id="icon-image-64"
src="/icon.png"
loading="eager"
width={64}
height={64}
/>
<Image
id="icon-image-16"
src="/icon.png"
loading="eager"
width={16}
height={16}
/>
<Link href="/client-side"> <Link href="/client-side">
<a id="clientlink">Client Side</a> <a id="clientlink">Client Side</a>
</Link> </Link>
......
...@@ -51,6 +51,20 @@ function runTests() { ...@@ -51,6 +51,20 @@ function runTests() {
await browser.elementById('preceding-slash-image').getAttribute('srcset') await browser.elementById('preceding-slash-image').getAttribute('srcset')
).toBe('https://example.com/myaccount/fooslash.jpg?auto=format&w=480 480w') ).toBe('https://example.com/myaccount/fooslash.jpg?auto=format&w=480 480w')
}) })
it('should use iconSizes when width matches, not deviceSizes from next.config.js', async () => {
expect(await browser.elementById('icon-image-16').getAttribute('src')).toBe(
'https://example.com/myaccount/icon.png?auto=format&w=16'
)
expect(
await browser.elementById('icon-image-16').getAttribute('srcset')
).toBe('https://example.com/myaccount/icon.png?auto=format&w=16 16w')
expect(await browser.elementById('icon-image-64').getAttribute('src')).toBe(
'https://example.com/myaccount/icon.png?auto=format&w=64'
)
expect(
await browser.elementById('icon-image-64').getAttribute('srcset')
).toBe('https://example.com/myaccount/icon.png?auto=format&w=64 64w')
})
it('should support the unoptimized attribute', async () => { it('should support the unoptimized attribute', async () => {
expect( expect(
await browser.elementById('unoptimized-image').getAttribute('src') await browser.elementById('unoptimized-image').getAttribute('src')
......
...@@ -348,12 +348,12 @@ describe('Image Optimizer', () => { ...@@ -348,12 +348,12 @@ describe('Image Optimizer', () => {
) )
}) })
it('should error when sizes length exceeds 50', async () => { it('should error when sizes length exceeds 25', async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
images: { images: {
sizes: new Array(51).fill(1024), deviceSizes: new Array(51).fill(1024),
}, },
}) })
) )
...@@ -369,16 +369,16 @@ describe('Image Optimizer', () => { ...@@ -369,16 +369,16 @@ describe('Image Optimizer', () => {
await nextConfig.restore() await nextConfig.restore()
expect(stderr).toContain( expect(stderr).toContain(
'Specified images.sizes exceeds length of 50, received length (51), please reduce the length of the array to continue' 'Specified images.deviceSizes exceeds length of 25, received length (51), please reduce the length of the array to continue'
) )
}) })
it('should error when sizes contains invalid sizes', async () => { it('should error when deviceSizes contains invalid widths', async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
images: { images: {
sizes: [0, 12000, 64, 128, 256], deviceSizes: [0, 12000, 64, 128, 256],
}, },
}) })
) )
...@@ -394,7 +394,32 @@ describe('Image Optimizer', () => { ...@@ -394,7 +394,32 @@ describe('Image Optimizer', () => {
await nextConfig.restore() await nextConfig.restore()
expect(stderr).toContain( expect(stderr).toContain(
'Specified images.sizes should be an Array of numbers that are between 1 and 10000, received invalid values (0, 12000)' 'Specified images.deviceSizes should be an Array of numbers that are between 1 and 10000, received invalid values (0, 12000)'
)
})
it('should error when iconSizes contains invalid widths', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
iconSizes: [0, 16, 64, 12000],
},
})
)
let stderr = ''
app = await launchApp(appDir, await findPort(), {
onStderr(msg) {
stderr += msg || ''
},
})
await waitFor(1000)
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(stderr).toContain(
'Specified images.iconSizes should be an Array of numbers that are between 1 and 10000, received invalid values (0, 12000)'
) )
}) })
}) })
...@@ -421,7 +446,8 @@ describe('Image Optimizer', () => { ...@@ -421,7 +446,8 @@ describe('Image Optimizer', () => {
beforeAll(async () => { beforeAll(async () => {
const json = JSON.stringify({ const json = JSON.stringify({
images: { images: {
sizes: [size, largeSize], deviceSizes: [largeSize],
iconSizes: [size],
domains, domains,
}, },
}) })
...@@ -458,7 +484,7 @@ describe('Image Optimizer', () => { ...@@ -458,7 +484,7 @@ describe('Image Optimizer', () => {
beforeAll(async () => { beforeAll(async () => {
const json = JSON.stringify({ const json = JSON.stringify({
images: { images: {
sizes: [size, largeSize], deviceSizes: [size, largeSize],
domains, domains,
}, },
}) })
...@@ -482,7 +508,7 @@ describe('Image Optimizer', () => { ...@@ -482,7 +508,7 @@ describe('Image Optimizer', () => {
const json = JSON.stringify({ const json = JSON.stringify({
target: 'experimental-serverless-trace', target: 'experimental-serverless-trace',
images: { images: {
sizes: [size, largeSize], deviceSizes: [size, largeSize],
domains, domains,
}, },
}) })
......
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