Unverified Commit 4cc7f11d authored by Steven's avatar Steven Committed by GitHub

Update to stable: `next/future/image`, `remotePatterns`, `unoptimized` (#40142)

This PR updates a few features from experimental to stable status:

- `next/future/image` component
- `remotePatterns` configuration
- `unoptimized` configuration
parent 643447ed
--- ---
description: Try the latest Image Optimization with the experimental `next/future/image` component. description: Try the latest Image Optimization with the new `next/future/image` component.
--- ---
# next/future/image # next/future/image
...@@ -7,29 +7,17 @@ description: Try the latest Image Optimization with the experimental `next/futur ...@@ -7,29 +7,17 @@ description: Try the latest Image Optimization with the experimental `next/futur
<details> <details>
<summary><b>Version History</b></summary> <summary><b>Version History</b></summary>
| Version | Changes | | Version | Changes |
| --------- | -------------------------------------------- | | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `v12.3.0` | Changed `alt` property to required. | | `v12.3.0` | `next/future/image` component stable. `remotePatterns` config stable. `unoptimized` config stable. `alt` property required. |
| `v12.2.4` | Support for `fill` property added. | | `v12.2.4` | `fill` property added. |
| `v12.2.0` | Experimental `next/future/image` introduced. | | `v12.2.0` | Experimental `next/future/image` component introduced. |
</details> </details>
The `next/future/image` component is an experiment to improve both the performance and developer experience of `next/image` by using the native `<img>` element with better default behavior. The `next/future/image` component improves both the performance and developer experience of `next/image` by using the native `<img>` element with better default behavior.
This new component is considered experimental and therefore not covered by semver, and may cause unexpected or broken application behavior. This component uses browser native [lazy loading](https://caniuse.com/loading-lazy-attr), which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with `width`/`height` of `auto`, it is possible to cause [Layout Shift](https://web.dev/cls/) on older browsers before Safari 15 that don't [preserve the aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes). For more details, see [this MDN video](https://www.youtube.com/watch?v=4-d_SoCHeWE). This component uses browser native [lazy loading](https://caniuse.com/loading-lazy-attr), which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with `width`/`height` of `auto`, it is possible to cause [Layout Shift](https://web.dev/cls/) on older browsers before Safari 15 that don't [preserve the aspect ratio](https://caniuse.com/mdn-html_elements_img_aspect_ratio_computed_from_attributes). For more details, see [this MDN video](https://www.youtube.com/watch?v=4-d_SoCHeWE).
To use `next/future/image`, add the following to your `next.config.js` file:
```js
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
```
## Comparison ## Comparison
...@@ -374,14 +362,12 @@ You can also [generate a solid color Data URL](https://png-pixel.com) to match t ...@@ -374,14 +362,12 @@ You can also [generate a solid color Data URL](https://png-pixel.com) to match t
When true, the source image will be served as-is instead of changing quality, When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to `false`. size, or format. Defaults to `false`.
This prop can be assigned to all images by updating `next.config.js` with the following experimental configuration: This prop can be assigned to all images by updating `next.config.js` with the following configuration:
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { unoptimized: true,
unoptimized: true,
},
}, },
} }
``` ```
...@@ -399,23 +385,19 @@ Other properties on the `<Image />` component will be passed to the underlying ...@@ -399,23 +385,19 @@ Other properties on the `<Image />` component will be passed to the underlying
### Remote Patterns ### Remote Patterns
> Note: The `remotePatterns` configuration is currently **experimental** and subject to change. Please use [`domains`](#domains) for production use cases.
To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below:
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [
remotePatterns: [ {
{ protocol: 'https',
protocol: 'https', hostname: 'example.com',
hostname: 'example.com', port: '',
port: '', pathname: '/account123/**',
pathname: '/account123/**', },
}, ],
],
},
}, },
} }
``` ```
...@@ -426,15 +408,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js ...@@ -426,15 +408,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [
remotePatterns: [ {
{ protocol: 'https',
protocol: 'https', hostname: '**.example.com',
hostname: '**.example.com', },
}, ],
],
},
}, },
} }
``` ```
......
...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes | | Version | Changes |
| --------- | --------------------------------------------------------------------------------------------------------- | | --------- | --------------------------------------------------------------------------------------------------------- |
| `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. |
| `v12.2.0` | Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. | | `v12.2.0` | Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. |
| `v12.1.1` | `style` prop added. Experimental[\*](#experimental-raw-layout-mode) support for `layout="raw"` added. | | `v12.1.1` | `style` prop added. Experimental[\*](#experimental-raw-layout-mode) support for `layout="raw"` added. |
| `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. | | `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. |
...@@ -93,8 +94,6 @@ The layout behavior of the image as the viewport changes size. ...@@ -93,8 +94,6 @@ The layout behavior of the image as the viewport changes size.
- When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative. - When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.
- This is usually paired with the [`objectFit`](#objectFit) property. - This is usually paired with the [`objectFit`](#objectFit) property.
- Ensure the parent element has `position: relative` in their stylesheet. - Ensure the parent element has `position: relative` in their stylesheet.
- When `raw`[\*](#experimental-raw-layout-mode), the image will be rendered as a single image element with no wrappers, sizers or other responsive behavior.
- If your image styling will change the size of a `raw` image, you should include the `sizes` property for proper image serving. Otherwise your image will be requested as though it has fixed width and height.
- [Demo background image](https://image-component.nextjs.gallery/background) - [Demo background image](https://image-component.nextjs.gallery/background)
### loader ### loader
...@@ -324,14 +323,12 @@ const Example = () => { ...@@ -324,14 +323,12 @@ const Example = () => {
When true, the source image will be served as-is instead of changing quality, When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to `false`. size, or format. Defaults to `false`.
This prop can be assigned to all images by updating `next.config.js` with the following experimental configuration: This prop can be assigned to all images by updating `next.config.js` with the following configuration:
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { unoptimized: true,
unoptimized: true,
},
}, },
} }
``` ```
...@@ -351,23 +348,19 @@ Other properties on the `<Image />` component will be passed to the underlying ...@@ -351,23 +348,19 @@ Other properties on the `<Image />` component will be passed to the underlying
### Remote Patterns ### Remote Patterns
> Note: The `remotePatterns` configuration is currently **experimental** and subject to change. Please use [`domains`](#domains) for production use cases.
To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below: To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below:
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [
remotePatterns: [ {
{ protocol: 'https',
protocol: 'https', hostname: 'example.com',
hostname: 'example.com', port: '',
port: '', pathname: '/account123/**',
pathname: '/account123/**', },
}, ],
],
},
}, },
} }
``` ```
...@@ -378,15 +371,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js ...@@ -378,15 +371,13 @@ Below is another example of the `remotePatterns` property in the `next.config.js
```js ```js
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [
remotePatterns: [ {
{ protocol: 'https',
protocol: 'https', hostname: '**.example.com',
hostname: '**.example.com', },
}, ],
],
},
}, },
} }
``` ```
......
...@@ -427,7 +427,7 @@ ...@@ -427,7 +427,7 @@
} }
}, },
{ {
"title": "next/future/image (experimental)", "title": "next/future/image",
"path": "/docs/api-reference/next/future/image.md" "path": "/docs/api-reference/next/future/image.md"
}, },
{ {
......
...@@ -31,17 +31,10 @@ module.exports = { ...@@ -31,17 +31,10 @@ module.exports = {
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
// set the Content-Security-Policy header // set the Content-Security-Policy header
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// the following are experimental features, and may cause breaking changes // limit of 50 objects
}, remotePatterns: [],
experimental: { // when true, every image will be unoptimized
images: { unoptimized: false,
// limit of 50 objects
remotePatterns: [],
// when true, every image will be unoptimized
unoptimized: false,
// when true, allow `next/future/image` to be imported
allowFutureImage: false,
},
}, },
} }
``` ```
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
images: { images: {
domains: ['cdn.sanity.io', 'source.unsplash.com'], remotePatterns: [
{ hostname: 'cdn.sanity.io' },
{ hostname: 'source.unsplash.com' },
],
}, },
} }
...@@ -2405,7 +2405,7 @@ export default async function build( ...@@ -2405,7 +2405,7 @@ export default async function build(
const { deviceSizes, imageSizes } = images const { deviceSizes, imageSizes } = images
;(images as any).sizes = [...deviceSizes, ...imageSizes] ;(images as any).sizes = [...deviceSizes, ...imageSizes]
;(images as any).remotePatterns = ( ;(images as any).remotePatterns = (
config?.experimental?.images?.remotePatterns || [] config?.images?.remotePatterns || []
).map((p: RemotePattern) => ({ ).map((p: RemotePattern) => ({
// Should be the same as matchRemotePattern() // Should be the same as matchRemotePattern()
protocol: p.protocol, protocol: p.protocol,
......
...@@ -196,14 +196,12 @@ export function getDefineEnv({ ...@@ -196,14 +196,12 @@ export function getDefineEnv({
path: config.images.path, path: config.images.path,
loader: config.images.loader, loader: config.images.loader,
dangerouslyAllowSVG: config.images.dangerouslyAllowSVG, dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
experimentalUnoptimized: config?.experimental?.images?.unoptimized, unoptimized: config?.images?.unoptimized,
experimentalFuture: config.experimental?.images?.allowFutureImage,
...(dev ...(dev
? { ? {
// pass domains in development to allow validating on the client // pass domains in development to allow validating on the client
domains: config.images.domains, domains: config.images.domains,
experimentalRemotePatterns: remotePatterns: config.images?.remotePatterns,
config.experimental?.images?.remotePatterns,
} }
: {}), : {}),
}), }),
......
...@@ -15,11 +15,6 @@ import { ...@@ -15,11 +15,6 @@ import {
import { ImageConfigContext } from '../../shared/lib/image-config-context' import { ImageConfigContext } from '../../shared/lib/image-config-context'
import { warnOnce } from '../../shared/lib/utils' import { warnOnce } from '../../shared/lib/utils'
const {
experimentalFuture = false,
experimentalRemotePatterns = [],
experimentalUnoptimized,
} = (process.env.__NEXT_IMAGE_OPTS as any) || {}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const allImgs = new Map< const allImgs = new Map<
string, string,
...@@ -475,10 +470,7 @@ function defaultLoader({ ...@@ -475,10 +470,7 @@ function defaultLoader({
) )
} }
if ( if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
!src.startsWith('/') &&
(config.domains || experimentalRemotePatterns)
) {
let parsedSrc: URL let parsedSrc: URL
try { try {
parsedSrc = new URL(src) parsedSrc = new URL(src)
...@@ -492,7 +484,7 @@ function defaultLoader({ ...@@ -492,7 +484,7 @@ function defaultLoader({
if (process.env.NODE_ENV !== 'test') { if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development // We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern') const { hasMatch } = require('../../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, experimentalRemotePatterns, parsedSrc)) { if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error( throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host` `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
...@@ -530,11 +522,6 @@ export default function Image({ ...@@ -530,11 +522,6 @@ export default function Image({
blurDataURL, blurDataURL,
...all ...all
}: ImageProps) { }: ImageProps) {
if (!experimentalFuture && process.env.NODE_ENV !== 'test') {
throw new Error(
`The "next/future/image" component is experimental and may be subject to breaking changes. To enable this experiment, please include \`experimental: { images: { allowFutureImage: true } }\` in your next.config.js file.`
)
}
const configContext = useContext(ImageConfigContext) const configContext = useContext(ImageConfigContext)
const config: ImageConfig = useMemo(() => { const config: ImageConfig = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault const c = configEnv || configContext || imageConfigDefault
...@@ -600,7 +587,7 @@ export default function Image({ ...@@ -600,7 +587,7 @@ export default function Image({
unoptimized = true unoptimized = true
isLazy = false isLazy = false
} }
if (experimentalUnoptimized) { if (config.unoptimized) {
unoptimized = true unoptimized = true
} }
......
...@@ -22,8 +22,6 @@ function normalizeSrc(src: string): string { ...@@ -22,8 +22,6 @@ function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src return src[0] === '/' ? src.slice(1) : src
} }
const { experimentalRemotePatterns = [], experimentalUnoptimized } =
(process.env.__NEXT_IMAGE_OPTS as any) || {}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>() const loadedImageURLs = new Set<string>()
const allImgs = new Map< const allImgs = new Map<
...@@ -137,10 +135,7 @@ function defaultLoader({ ...@@ -137,10 +135,7 @@ function defaultLoader({
) )
} }
if ( if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
!src.startsWith('/') &&
(config.domains || experimentalRemotePatterns)
) {
let parsedSrc: URL let parsedSrc: URL
try { try {
parsedSrc = new URL(src) parsedSrc = new URL(src)
...@@ -154,7 +149,7 @@ function defaultLoader({ ...@@ -154,7 +149,7 @@ function defaultLoader({
if (process.env.NODE_ENV !== 'test') { if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development // We use dynamic require because this should only error in development
const { hasMatch } = require('../shared/lib/match-remote-pattern') const { hasMatch } = require('../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, experimentalRemotePatterns, parsedSrc)) { if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error( throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host` `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
...@@ -673,7 +668,7 @@ export default function Image({ ...@@ -673,7 +668,7 @@ export default function Image({
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) { if (typeof window !== 'undefined' && loadedImageURLs.has(src)) {
isLazy = false isLazy = false
} }
if (experimentalUnoptimized) { if (config.unoptimized) {
unoptimized = true unoptimized = true
} }
......
...@@ -321,8 +321,7 @@ export default async function exportApp( ...@@ -321,8 +321,7 @@ export default async function exportApp(
const { const {
i18n, i18n,
images: { loader = 'default' }, images: { loader = 'default', unoptimized },
experimental,
} = nextConfig } = nextConfig
if (i18n && !options.buildExport) { if (i18n && !options.buildExport) {
...@@ -344,7 +343,7 @@ export default async function exportApp( ...@@ -344,7 +343,7 @@ export default async function exportApp(
if ( if (
isNextImageImported && isNextImageImported &&
loader === 'default' && loader === 'default' &&
!experimental?.images?.unoptimized && !unoptimized &&
!hasNextSupport !hasNextSupport
) { ) {
throw new Error( throw new Error(
......
...@@ -270,44 +270,6 @@ const configSchema = { ...@@ -270,44 +270,6 @@ const configSchema = {
gzipSize: { gzipSize: {
type: 'boolean', type: 'boolean',
}, },
images: {
additionalProperties: false,
properties: {
allowFutureImage: {
type: 'boolean',
},
remotePatterns: {
items: {
additionalProperties: false,
properties: {
hostname: {
minLength: 1,
type: 'string',
},
pathname: {
minLength: 1,
type: 'string',
},
port: {
minLength: 1,
type: 'string',
},
protocol: {
// automatic typing doesn't like enum
enum: ['http', 'https'] as any,
type: 'string',
},
},
type: 'object',
},
type: 'array',
},
unoptimized: {
type: 'boolean',
},
},
type: 'object',
},
incrementalCacheHandlerPath: { incrementalCacheHandlerPath: {
type: 'string', type: 'string',
}, },
...@@ -487,6 +449,35 @@ const configSchema = { ...@@ -487,6 +449,35 @@ const configSchema = {
images: { images: {
additionalProperties: false, additionalProperties: false,
properties: { properties: {
remotePatterns: {
items: {
additionalProperties: false,
properties: {
hostname: {
minLength: 1,
type: 'string',
},
pathname: {
minLength: 1,
type: 'string',
},
port: {
minLength: 1,
type: 'string',
},
protocol: {
// automatic typing doesn't like enum
enum: ['http', 'https'] as any,
type: 'string',
},
},
type: 'object',
},
type: 'array',
},
unoptimized: {
type: 'boolean',
},
contentSecurityPolicy: { contentSecurityPolicy: {
minLength: 1, minLength: 1,
type: 'string', type: 'string',
......
...@@ -5,7 +5,6 @@ import { ...@@ -5,7 +5,6 @@ import {
ImageConfig, ImageConfig,
ImageConfigComplete, ImageConfigComplete,
imageConfigDefault, imageConfigDefault,
RemotePattern,
} from '../shared/lib/image-config' } from '../shared/lib/image-config'
import { ServerRuntime } from 'next/types' import { ServerRuntime } from 'next/types'
...@@ -117,11 +116,6 @@ export interface ExperimentalConfig { ...@@ -117,11 +116,6 @@ export interface ExperimentalConfig {
fullySpecified?: boolean fullySpecified?: boolean
urlImports?: NonNullable<webpack.Configuration['experiments']>['buildHttp'] urlImports?: NonNullable<webpack.Configuration['experiments']>['buildHttp']
outputFileTracingRoot?: string outputFileTracingRoot?: string
images?: {
remotePatterns?: RemotePattern[]
unoptimized?: boolean
allowFutureImage?: boolean
}
modularizeImports?: Record< modularizeImports?: Record<
string, string,
{ {
...@@ -572,9 +566,6 @@ export const defaultConfig: NextConfig = { ...@@ -572,9 +566,6 @@ export const defaultConfig: NextConfig = {
serverComponents: false, serverComponents: false,
fullySpecified: false, fullySpecified: false,
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '', outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
images: {
remotePatterns: [],
},
swcTraceProfiling: false, swcTraceProfiling: false,
forceSwcTransforms: false, forceSwcTransforms: false,
swcPlugins: undefined, swcPlugins: undefined,
......
...@@ -256,7 +256,7 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -256,7 +256,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
} }
} }
const remotePatterns = result.experimental?.images?.remotePatterns const remotePatterns = result?.images?.remotePatterns
if (remotePatterns) { if (remotePatterns) {
if (!Array.isArray(remotePatterns)) { if (!Array.isArray(remotePatterns)) {
throw new Error( throw new Error(
...@@ -437,7 +437,7 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -437,7 +437,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
) )
} }
const unoptimized = result.experimental?.images?.unoptimized const unoptimized = result?.images?.unoptimized
if ( if (
typeof unoptimized !== 'undefined' && typeof unoptimized !== 'undefined' &&
typeof unoptimized !== 'boolean' typeof unoptimized !== 'boolean'
......
...@@ -161,7 +161,7 @@ export class ImageOptimizerCache { ...@@ -161,7 +161,7 @@ export class ImageOptimizerCache {
minimumCacheTTL = 60, minimumCacheTTL = 60,
formats = ['image/webp'], formats = ['image/webp'],
} = imageData } = imageData
const remotePatterns = nextConfig.experimental.images?.remotePatterns || [] const remotePatterns = nextConfig.images?.remotePatterns || []
const { url, w, q } = query const { url, w, q } = query
let href: string let href: string
......
...@@ -74,6 +74,12 @@ export type ImageConfigComplete = { ...@@ -74,6 +74,12 @@ export type ImageConfigComplete = {
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */ /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
contentSecurityPolicy: string contentSecurityPolicy: string
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remote-patterns) */
remotePatterns: RemotePattern[]
/** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */
unoptimized: boolean
} }
export type ImageConfig = Partial<ImageConfigComplete> export type ImageConfig = Partial<ImageConfigComplete>
...@@ -89,4 +95,6 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -89,4 +95,6 @@ export const imageConfigDefault: ImageConfigComplete = {
formats: ['image/webp'], formats: ['image/webp'],
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`, contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
remotePatterns: [],
unoptimized: false,
} }
...@@ -81,7 +81,7 @@ export function eventCliSession( ...@@ -81,7 +81,7 @@ export function eventCliSession(
return [] return []
} }
const { images, i18n, experimental } = nextConfig || {} const { images, i18n } = nextConfig || {}
const payload: EventCliSessionStarted = { const payload: EventCliSessionStarted = {
nextVersion: process.env.__NEXT_VERSION, nextVersion: process.env.__NEXT_VERSION,
...@@ -95,15 +95,15 @@ export function eventCliSession( ...@@ -95,15 +95,15 @@ export function eventCliSession(
hasWebpackConfig: typeof nextConfig?.webpack === 'function', hasWebpackConfig: typeof nextConfig?.webpack === 'function',
hasBabelConfig: hasBabelConfig(dir), hasBabelConfig: hasBabelConfig(dir),
imageEnabled: !!images, imageEnabled: !!images,
imageFutureEnabled: !!experimental.images?.allowFutureImage, imageFutureEnabled: !!images,
basePathEnabled: !!nextConfig?.basePath, basePathEnabled: !!nextConfig?.basePath,
i18nEnabled: !!i18n, i18nEnabled: !!i18n,
locales: i18n?.locales ? i18n.locales.join(',') : null, locales: i18n?.locales ? i18n.locales.join(',') : null,
localeDomainsCount: i18n?.domains ? i18n.domains.length : null, localeDomainsCount: i18n?.domains ? i18n.domains.length : null,
localeDetectionEnabled: !i18n ? null : i18n.localeDetection !== false, localeDetectionEnabled: !i18n ? null : i18n.localeDetection !== false,
imageDomainsCount: images?.domains ? images.domains.length : null, imageDomainsCount: images?.domains ? images.domains.length : null,
imageRemotePatternsCount: experimental?.images?.remotePatterns imageRemotePatternsCount: images?.remotePatterns
? experimental.images.remotePatterns.length ? images.remotePatterns.length
: null, : null,
imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null, imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null,
imageLoader: images?.loader, imageLoader: images?.loader,
......
...@@ -87,10 +87,8 @@ describe('Export with unoptimized next/image component', () => { ...@@ -87,10 +87,8 @@ describe('Export with unoptimized next/image component', () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
experimental: { images: {
images: { unoptimized: true,
unoptimized: true,
},
}, },
}) })
) )
......
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
},
}, },
} }
module.exports = { module.exports = {
experimental: { images: {
images: { unoptimized: true,
unoptimized: true,
},
}, },
} }
module.exports = { module.exports = {
assetPrefix: 'https://example.vercel.sh/pre', assetPrefix: 'https://example.vercel.sh/pre',
// Intentionally omit `domains` and `remotePatterns` // Intentionally omit `domains` and `remotePatterns`
experimental: {
images: {
allowFutureImage: true,
},
},
} }
module.exports = { module.exports = {
basePath: '/docs', basePath: '/docs',
experimental: {
images: {
allowFutureImage: true,
},
},
} }
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
...@@ -2,9 +2,4 @@ module.exports = { ...@@ -2,9 +2,4 @@ module.exports = {
images: { images: {
domains: ['i.imgur.com'], domains: ['i.imgur.com'],
}, },
experimental: {
images: {
allowFutureImage: true,
},
},
} }
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
...@@ -10,9 +10,4 @@ module.exports = { ...@@ -10,9 +10,4 @@ module.exports = {
return config return config
}, },
experimental: {
images: {
allowFutureImage: true,
},
},
} }
module.exports = { module.exports = {
trailingSlash: true, trailingSlash: true,
experimental: {
images: {
allowFutureImage: true,
},
},
} }
...@@ -3,9 +3,4 @@ module.exports = { ...@@ -3,9 +3,4 @@ module.exports = {
domains: ['image-optimization-test.vercel.app'], domains: ['image-optimization-test.vercel.app'],
// disableStaticImages: true, // disableStaticImages: true,
}, },
experimental: {
images: {
allowFutureImage: true,
},
},
} }
module.exports = { module.exports = {
experimental: { images: {
images: { remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
remotePatterns: [{ hostname: 'image-optimization-test.vercel.app' }],
allowFutureImage: true,
},
}, },
} }
module.exports = { module.exports = {
experimental: { images: {
images: { unoptimized: true,
unoptimized: true,
allowFutureImage: true,
},
}, },
} }
...@@ -52,12 +52,10 @@ describe('Image Optimizer', () => { ...@@ -52,12 +52,10 @@ describe('Image Optimizer', () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
experimental: { images: {
images: { remotePatterns: Array.from({ length: 51 }).map((_) => ({
remotePatterns: Array.from({ length: 51 }).map((_) => ({ hostname: 'example.com',
hostname: 'example.com', })),
})),
},
}, },
}) })
) )
...@@ -81,10 +79,8 @@ describe('Image Optimizer', () => { ...@@ -81,10 +79,8 @@ describe('Image Optimizer', () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
experimental: { images: {
images: { remotePatterns: [{ hostname: 'example.com', foo: 'bar' }],
remotePatterns: [{ hostname: 'example.com', foo: 'bar' }],
},
}, },
}) })
) )
...@@ -108,10 +104,8 @@ describe('Image Optimizer', () => { ...@@ -108,10 +104,8 @@ describe('Image Optimizer', () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
JSON.stringify({ JSON.stringify({
experimental: { images: {
images: { remotePatterns: [{ protocol: 'https' }],
remotePatterns: [{ protocol: 'https' }],
},
}, },
}) })
) )
......
...@@ -4,11 +4,7 @@ module.exports = phase => { ...@@ -4,11 +4,7 @@ module.exports = phase => {
formats: ['image/avif', 'image/webp'], formats: ['image/avif', 'image/webp'],
imageSizes: [64, 128, 256, 512, 1024], imageSizes: [64, 128, 256, 512, 1024],
domains: ['example.com', 'another.com'], domains: ['example.com', 'another.com'],
}, remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }],
experimental: {
images: {
remotePatterns: [{ protocol: 'https', hostname: '**.example.com' }],
},
}, },
i18n: { i18n: {
locales: ['en','nl','fr'], locales: ['en','nl','fr'],
......
...@@ -503,7 +503,7 @@ describe('Telemetry CLI', () => { ...@@ -503,7 +503,7 @@ describe('Telemetry CLI', () => {
expect(event1).toMatch(/"localeDomainsCount": 2/) expect(event1).toMatch(/"localeDomainsCount": 2/)
expect(event1).toMatch(/"localeDetectionEnabled": true/) expect(event1).toMatch(/"localeDetectionEnabled": true/)
expect(event1).toMatch(/"imageEnabled": true/) expect(event1).toMatch(/"imageEnabled": true/)
expect(event1).toMatch(/"imageFutureEnabled": false/) expect(event1).toMatch(/"imageFutureEnabled": true/)
expect(event1).toMatch(/"imageDomainsCount": 2/) expect(event1).toMatch(/"imageDomainsCount": 2/)
expect(event1).toMatch(/"imageRemotePatternsCount": 1/) expect(event1).toMatch(/"imageRemotePatternsCount": 1/)
expect(event1).toMatch(/"imageSizes": "64,128,256,512,1024"/) expect(event1).toMatch(/"imageSizes": "64,128,256,512,1024"/)
......
...@@ -2,10 +2,8 @@ ...@@ -2,10 +2,8 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
experimental: { images: {
images: { dangerouslyAllowSVG: true,
allowFutureImage: true,
},
}, },
} }
......
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