Unverified Commit 7102050e authored by Steven's avatar Steven Committed by GitHub

Add support for `images.loaderFile` config (#41585)

This PR adds a new configure property, `images.loaderFile` that allow
you to define a path to a file with an exported image loader function.

This is useful when migrating from `next/legacy/image` to `next/image`
because it lets you configure the loader for every instance of
`next/image` once, similar to the legacy "built-in loaders".
parent 6f43c90b
...@@ -111,6 +111,8 @@ const MyImage = (props) => { ...@@ -111,6 +111,8 @@ const MyImage = (props) => {
} }
``` ```
Alternatively, you can use the [loaderFile](#loader-configuration) configuration in next.config.js to configure every instance of `next/image` in your application, without passing a prop.
### fill ### fill
A boolean that causes the image to fill the parent element instead of setting [`width`](#width) and [`height`](#height). A boolean that causes the image to fill the parent element instead of setting [`width`](#width) and [`height`](#height).
...@@ -343,6 +345,29 @@ module.exports = { ...@@ -343,6 +345,29 @@ module.exports = {
} }
``` ```
### Loader Configuration
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the `loaderFile` in your `next.config.js` like the following:
```js
module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
```
This must point to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example:
```js
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
```
Alternatively, you can use the [`loader` prop](#loader) to configure each instance of `next/image`.
## Advanced ## Advanced
The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates. The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
......
...@@ -99,13 +99,13 @@ To protect your application from malicious users, you must define a list of remo ...@@ -99,13 +99,13 @@ To protect your application from malicious users, you must define a list of remo
### Loaders ### Loaders
Note that in the [example earlier](#remote-images), a partial URL (`"/me.png"`) is provided for a remote image. This is possible because of the `next/image` [loader](/docs/api-reference/next/image.md#loader) architecture. Note that in the [example earlier](#remote-images), a partial URL (`"/me.png"`) is provided for a remote image. This is possible because of the loader architecture.
A loader is a function that generates the URLs for your image. It modifies the provided `src`, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) generation, so that visitors to your site will be served an image that is the right size for their viewport. A loader is a function that generates the URLs for your image. It modifies the provided `src`, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic [srcset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) generation, so that visitors to your site will be served an image that is the right size for their viewport.
The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can use one of the [built-in loaders](/docs/api-reference/next/image.md#built-in-loaders) or write your own with a few lines of JavaScript. The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can write your own loader function with a few lines of JavaScript.
Loaders can be defined per-image, or at the application level. You can define a loader per-image with the [`loader` prop](/docs/api-reference/next/image.md#loader), or at the application level with the [`loaderFile` configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration).
### Priority ### Priority
...@@ -151,7 +151,7 @@ Because `next/image` is designed to guarantee good performance results, it canno ...@@ -151,7 +151,7 @@ Because `next/image` is designed to guarantee good performance results, it canno
> >
> If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do: > If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do:
> >
> **Use `fill``** > **Use `fill`**
> >
> The [`fill`](/docs/api-reference/next/image#fill) prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along [`sizes`](/docs/api-reference/next/image#sizes) prop to match any media query break points. You can also use [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) with `fill`, `contain`, or `cover`, and [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) to define how the image should occupy that space. > The [`fill`](/docs/api-reference/next/image#fill) prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along [`sizes`](/docs/api-reference/next/image#sizes) prop to match any media query break points. You can also use [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) with `fill`, `contain`, or `cover`, and [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) to define how the image should occupy that space.
> >
......
...@@ -21,6 +21,8 @@ module.exports = { ...@@ -21,6 +21,8 @@ module.exports = {
path: '/_next/image', path: '/_next/image',
// loader can be 'default', 'imgix', 'cloudinary', 'akamai', or 'custom' // loader can be 'default', 'imgix', 'cloudinary', 'akamai', or 'custom'
loader: 'default', loader: 'default',
// file with `export default function loader({src, width, quality})`
loaderFile: '',
// disable static imports for image files // disable static imports for image files
disableStaticImages: false, disableStaticImages: false,
// minimumCacheTTL is in seconds, must be integer 0 or more // minimumCacheTTL is in seconds, must be integer 0 or more
......
...@@ -866,6 +866,12 @@ export default async function getBaseWebpackConfig( ...@@ -866,6 +866,12 @@ export default async function getBaseWebpackConfig(
} }
: undefined), : undefined),
...(config.images.loaderFile
? {
'next/dist/shared/lib/image-loader': config.images.loaderFile,
}
: undefined),
next: NEXT_PROJECT_ROOT, next: NEXT_PROJECT_ROOT,
...(hasServerComponents ...(hasServerComponents
......
...@@ -16,6 +16,8 @@ import { ...@@ -16,6 +16,8 @@ import {
} from '../shared/lib/image-config' } from '../shared/lib/image-config'
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'
// @ts-ignore - This is replaced by webpack alias
import defaultLoader from 'next/dist/shared/lib/image-loader'
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<
...@@ -468,70 +470,6 @@ const ImageElement = ({ ...@@ -468,70 +470,6 @@ const ImageElement = ({
) )
} }
function defaultLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`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`
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${
quality || 75
}`
}
export default function Image({ export default function Image({
src, src,
sizes, sizes,
...@@ -559,20 +497,29 @@ export default function Image({ ...@@ -559,20 +497,29 @@ export default function Image({
}, [configContext]) }, [configContext])
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
let loader: ImageLoaderWithConfig = rest.loader || defaultLoader
let loader: ImageLoaderWithConfig = defaultLoader // Remove property so it's not spread on <img> element
if ('loader' in rest) { delete rest.loader
if (rest.loader) {
const customImageLoader = rest.loader if ('__next_img_default' in loader) {
loader = (obj) => { // This special value indicates that the user
const { config: _, ...opts } = obj // didn't define a "loader" prop or config.
// The config object is internal only so we must if (config.loader === 'custom') {
// not pass it to the user-defined loader() throw new Error(
return customImageLoader(opts) `Image with src "${src}" is missing "loader" prop.` +
} `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`
)
}
} else {
// The user defined a "loader" prop or config.
// Since the config object is internal only, we
// must not pass it to the user-defined "loader".
const customImageLoader = loader as ImageLoader
loader = (obj) => {
const { config: _, ...opts } = obj
return customImageLoader(opts)
} }
// Remove property so it's not spread on <img>
delete rest.loader
} }
let staticSrc = '' let staticSrc = ''
......
...@@ -585,6 +585,10 @@ const configSchema = { ...@@ -585,6 +585,10 @@ const configSchema = {
enum: VALID_LOADERS as any, enum: VALID_LOADERS as any,
type: 'string', type: 'string',
}, },
loaderFile: {
minLength: 1,
type: 'string',
},
minimumCacheTTL: { minimumCacheTTL: {
type: 'number', type: 'number',
}, },
......
import { basename, extname, relative, isAbsolute, resolve } from 'path' import { existsSync } from 'fs'
import { basename, extname, join, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url' import { pathToFileURL } from 'url'
import { Agent as HttpAgent } from 'http' import { Agent as HttpAgent } from 'http'
import { Agent as HttpsAgent } from 'https' import { Agent as HttpsAgent } from 'https'
...@@ -76,7 +77,7 @@ export function setHttpClientAndAgentOptions(options: NextConfig) { ...@@ -76,7 +77,7 @@ export function setHttpClientAndAgentOptions(options: NextConfig) {
;(global as any).__NEXT_HTTPS_AGENT = new HttpsAgent(options.httpAgentOptions) ;(global as any).__NEXT_HTTPS_AGENT = new HttpsAgent(options.httpAgentOptions)
} }
function assignDefaults(userConfig: { [key: string]: any }) { function assignDefaults(dir: string, userConfig: { [key: string]: any }) {
const configFileName = userConfig.configFileName const configFileName = userConfig.configFileName
if (typeof userConfig.exportTrailingSlash !== 'undefined') { if (typeof userConfig.exportTrailingSlash !== 'undefined') {
console.warn( console.warn(
...@@ -379,7 +380,7 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -379,7 +380,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
images.path === imageConfigDefault.path images.path === imageConfigDefault.path
) { ) {
throw new Error( throw new Error(
`Specified images.loader property (${images.loader}) also requires images.path property to be assigned to a URL prefix.\nSee more info here: https://nextjs.org/docs/api-reference/next/image#loader-configuration` `Specified images.loader property (${images.loader}) also requires images.path property to be assigned to a URL prefix.\nSee more info here: https://nextjs.org/docs/api-reference/next/legacy/image#loader-configuration`
) )
} }
...@@ -398,6 +399,22 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -398,6 +399,22 @@ function assignDefaults(userConfig: { [key: string]: any }) {
images.path = `${result.basePath}${images.path}` images.path = `${result.basePath}${images.path}`
} }
if (images.loaderFile) {
if (images.loader !== 'default' && images.loader !== 'custom') {
throw new Error(
`Specified images.loader property (${images.loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`
)
}
const absolutePath = join(dir, images.loaderFile)
if (!existsSync(absolutePath)) {
throw new Error(
`Specified images.loaderFile does not exist at "${absolutePath}".`
)
}
images.loader = 'custom'
images.loaderFile = absolutePath
}
if ( if (
images.minimumCacheTTL && images.minimumCacheTTL &&
(!Number.isInteger(images.minimumCacheTTL) || images.minimumCacheTTL < 0) (!Number.isInteger(images.minimumCacheTTL) || images.minimumCacheTTL < 0)
...@@ -739,7 +756,7 @@ export default async function loadConfig( ...@@ -739,7 +756,7 @@ export default async function loadConfig(
let configFileName = 'next.config.js' let configFileName = 'next.config.js'
if (customConfig) { if (customConfig) {
return assignDefaults({ return assignDefaults(dir, {
configOrigin: 'server', configOrigin: 'server',
configFileName, configFileName,
...customConfig, ...customConfig,
...@@ -818,7 +835,7 @@ export default async function loadConfig( ...@@ -818,7 +835,7 @@ export default async function loadConfig(
: canonicalBase) || '' : canonicalBase) || ''
} }
return assignDefaults({ return assignDefaults(dir, {
configOrigin: relative(dir, path), configOrigin: relative(dir, path),
configFile: path, configFile: path,
configFileName, configFileName,
...@@ -846,7 +863,10 @@ export default async function loadConfig( ...@@ -846,7 +863,10 @@ export default async function loadConfig(
// always call assignDefaults to ensure settings like // always call assignDefaults to ensure settings like
// reactRoot can be updated correctly even with no next.config.js // reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults(defaultConfig) as NextConfigComplete const completeConfig = assignDefaults(
dir,
defaultConfig
) as NextConfigComplete
completeConfig.configFileName = configFileName completeConfig.configFileName = configFileName
setHttpClientAndAgentOptions(completeConfig) setHttpClientAndAgentOptions(completeConfig)
return completeConfig return completeConfig
......
...@@ -49,12 +49,15 @@ export type ImageConfigComplete = { ...@@ -49,12 +49,15 @@ export type ImageConfigComplete = {
/** @see [Image sizing documentation](https://nextjs.org/docs/basic-features/image-optimization#image-sizing) */ /** @see [Image sizing documentation](https://nextjs.org/docs/basic-features/image-optimization#image-sizing) */
imageSizes: number[] imageSizes: number[]
/** @see [Image loaders configuration](https://nextjs.org/docs/basic-features/image-optimization#loaders) */ /** @see [Image loaders configuration](https://nextjs.org/docs/api-reference/next/legacy/image#loader) */
loader: LoaderValue loader: LoaderValue
/** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration) */ /** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/legacy/image#loader-configuration) */
path: string path: string
/** @see [Image loader configuration](https://nextjs.org/docs/api-reference/next/image#loader-configuration) */
loaderFile: string
/** /**
* @see [Image domains configuration](https://nextjs.org/docs/api-reference/next/image#domains) * @see [Image domains configuration](https://nextjs.org/docs/api-reference/next/image#domains)
*/ */
...@@ -89,6 +92,7 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -89,6 +92,7 @@ export const imageConfigDefault: ImageConfigComplete = {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: '/_next/image', path: '/_next/image',
loader: 'default', loader: 'default',
loaderFile: '',
domains: [], domains: [],
disableStaticImages: false, disableStaticImages: false,
minimumCacheTTL: 60, minimumCacheTTL: 60,
......
// TODO: change "any" to actual type
function defaultLoader({ config, src, width, quality }: any): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('./match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`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`
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${
quality || 75
}`
}
// We use this to determine if the import is the default loader
// or a custom loader defined by the user in next.config.js
defaultLoader.__next_img_default = true
export default defaultLoader
// prettier-ignore
module.exports = { /* replaceme */ }
import Image from 'next/legacy/image'
const loader = undefined
export default () => (
<div>
<p>Should succeed during export</p>
<Image alt="icon" src="/i.png" width="10" height="10" loader={loader} />
</div>
)
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport, File } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js'))
const pagesIndexJs = new File(join(appDir, 'pages', 'index.js'))
describe('Export with cloudinary loader next/legacy/image component', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'cloudinary',
path: 'https://example.com/',
},
})
)
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
expect($('img[alt="icon"]').attr('alt')).toBe('icon')
})
afterAll(async () => {
await nextConfig.restore()
})
})
describe('Export with custom loader next/legacy/image component', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
},
})
)
await pagesIndexJs.replace(
'loader = undefined',
'loader = ({src}) => "/custom" + src'
)
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
expect($('img[src="/custom/o.png"]')).toBeDefined()
})
afterAll(async () => {
await nextConfig.restore()
await pagesIndexJs.restore()
})
})
describe('Export with custom loader config but no loader prop on next/legacy/image', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
},
})
)
})
it('should fail build', async () => {
await fs.remove(join(appDir, '.next'))
const { code, stderr } = await nextBuild(appDir, [], { stderr: true })
expect(code).toBe(1)
expect(stderr).toContain(
'Error: Image with src "/i.png" is missing "loader" prop'
)
})
afterAll(async () => {
await nextConfig.restore()
await pagesIndexJs.restore()
})
})
describe('Export with unoptimized next/legacy/image component', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
unoptimized: true,
},
})
)
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
expect($('img[src="/o.png"]')).toBeDefined()
})
afterAll(async () => {
await nextConfig.restore()
})
})
export default function dummyLoader({ src, width, quality }) {
return `${src}#w:${width},q:${quality || 50}`
}
...@@ -82,6 +82,67 @@ describe('Export with custom loader next/image component', () => { ...@@ -82,6 +82,67 @@ describe('Export with custom loader next/image component', () => {
}) })
}) })
describe('Export with custom loader config but no loader prop on next/image', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
},
})
)
})
it('should fail build', async () => {
await fs.remove(join(appDir, '.next'))
const { code, stderr } = await nextBuild(appDir, [], { stderr: true })
expect(code).toBe(1)
expect(stderr).toContain(
'Error: Image with src "/i.png" is missing "loader" prop'
)
})
afterAll(async () => {
await nextConfig.restore()
await pagesIndexJs.restore()
})
})
describe('Export with loaderFile config next/image component', () => {
beforeAll(async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
loaderFile: './dummy-loader.js',
},
})
)
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
expect($('img[src="/i.png#w:32,q:50"]')).toBeDefined()
})
afterAll(async () => {
await nextConfig.restore()
await pagesIndexJs.restore()
})
})
describe('Export with unoptimized next/image component', () => { describe('Export with unoptimized next/image component', () => {
beforeAll(async () => { beforeAll(async () => {
await nextConfig.replace( await nextConfig.replace(
......
...@@ -274,6 +274,56 @@ describe('Image Optimizer', () => { ...@@ -274,6 +274,56 @@ describe('Image Optimizer', () => {
) )
}) })
it('should error when images.loader and images.loaderFile are both assigned', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'imgix',
path: 'https://example.com',
loaderFile: './dummy.js',
},
})
)
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.loader property (imgix) cannot be used with images.loaderFile property. Please set images.loader to "custom".`
)
})
it('should error when images.loaderFile does not exist', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loaderFile: './fakefile.js',
},
})
)
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.loaderFile does not exist at`)
})
it('should error when images.dangerouslyAllowSVG is not a boolean', async () => { it('should error when images.dangerouslyAllowSVG is not a boolean', async () => {
await nextConfig.replace( await nextConfig.replace(
'{ /* replaceme */ }', '{ /* replaceme */ }',
......
export default function dummyLoader({ src, width, quality }) {
return `${src}#w:${width},q:${quality || 50}`
}
module.exports = {
images: {
loader: 'custom',
loaderFile: './dummy-loader.js',
},
}
import React from 'react'
import Image from 'next/image'
function loader({ src, width, quality }) {
return `${src}?wid=${width}&qual=${quality || 35}`
}
const Page = () => {
return (
<div>
<h1>Loader Config</h1>
<Image
id="img1"
alt="img1"
src="/logo.png"
width="400"
height="400"
priority
/>
<p>Scroll down...</p>
<div style={{ height: '100vh' }} />
<h2>Loader Prop</h2>
<Image
id="img2"
alt="img2"
src="/logo.png"
width="200"
height="200"
loader={loader}
/>
</div>
)
}
export default Page
/* eslint-env jest */
import {
findPort,
killApp,
launchApp,
nextBuild,
nextStart,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
const appDir = join(__dirname, '../')
let appPort
let app
let browser
function runTests() {
it('should add "src" to img1 based on the loader config', async () => {
expect(await browser.elementById('img1').getAttribute('src')).toBe(
'/logo.png#w:828,q:50'
)
})
it('should add "srcset" to img1 based on the loader config', async () => {
expect(await browser.elementById('img1').getAttribute('srcset')).toBe(
'/logo.png#w:640,q:50 1x, /logo.png#w:828,q:50 2x'
)
})
it('should add "src" to img2 based on the loader prop', async () => {
expect(await browser.elementById('img2').getAttribute('src')).toBe(
'/logo.png?wid=640&qual=35'
)
})
it('should add "srcset" to img2 based on the loader prop', async () => {
expect(await browser.elementById('img2').getAttribute('srcset')).toBe(
'/logo.png?wid=256&qual=35 1x, /logo.png?wid=640&qual=35 2x'
)
})
}
describe('Image Loader Config', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
browser = await webdriver(appPort, '/')
})
afterAll(() => {
killApp(app)
if (browser) {
browser.close()
}
})
runTests()
})
describe('server mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
browser = await webdriver(appPort, '/')
})
afterAll(() => {
killApp(app)
if (browser) {
browser.close()
}
})
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