Unverified Commit 917d594c authored by Steven's avatar Steven Committed by GitHub

Print error during `next export` with default image loader (#19032)

Fixes #18356 
parent d40d7d65
......@@ -71,3 +71,4 @@ By default, `next export` will generate an `out` directory, which can be served
- The [`fallback: true`](/docs/basic-features/data-fetching.md#fallback-true) mode of `getStaticPaths` is not supported when using `next export`.
- [API Routes](/docs/api-routes/introduction.md) are not supported by this method because they can't be prerendered to HTML.
- [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) cannot be used within pages because the method requires a server. Consider using [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) instead.
- The [`next/image`](/docs/api-reference/next/image) component's default loader is not supported when using `next export`. However, other [loader](https://nextjs.org/docs/basic-features/image-optimization#loader) options will work.
# `next export` with Image API
#### Why This Error Occurred
You are attempting to run `next export` while importing the `next/image` component configured using the default `loader`.
However, the default `loader` relies on the Image Optimization API which is not available for exported applications.
This is because Next.js optimizes images on-demand, as users request them (not at build time).
#### Possible Ways to Fix It
- Use `next start` to run a server, which includes the Image Optimization API.
- Use Vercel to deploy, which supports [Image Optimization](https://vercel.com/docs/next.js/image-optimization).
- Configure a third-party [loader](https://nextjs.org/docs/basic-features/image-optimization#loader) in `next.config.js`.
### Useful Links
- [Deployment Documentation](https://nextjs.org/docs/deployment#vercel-recommended)
- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)
- [`next export` Documentation](https://nextjs.org/docs/advanced-features/static-html-export)
- [`next/image` Documentation](https://nextjs.org/docs/api-reference/next/image)
- [Vercel Documentation](https://vercel.com/docs/next.js/image-optimization)
......@@ -495,6 +495,7 @@ export default async function build(
let customAppGetInitialProps: boolean | undefined
let namedExports: Array<string> | undefined
let isNextImageImported: boolean | undefined
process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD
......@@ -585,6 +586,10 @@ export default async function build(
hybridAmpPages.add(page)
}
if (workerResult.isNextImageImported) {
isNextImageImported = true
}
if (workerResult.hasStaticProps) {
ssgPages.add(page)
isSsg = true
......@@ -1132,6 +1137,7 @@ export default async function build(
version: 1,
hasExportPathMap: typeof config.exportPathMap === 'function',
exportTrailingSlash: config.trailingSlash === true,
isNextImageImported: isNextImageImported === true,
}),
'utf8'
)
......
......@@ -701,6 +701,7 @@ export async function isPageStatic(
hasStaticProps?: boolean
prerenderRoutes?: string[] | undefined
prerenderFallback?: boolean | 'blocking' | undefined
isNextImageImported?: boolean
}> {
try {
require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
......@@ -788,6 +789,7 @@ export async function isPageStatic(
))
}
const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED
const config = mod.config || {}
return {
isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps,
......@@ -797,6 +799,7 @@ export async function isPageStatic(
prerenderFallback,
hasStaticProps,
hasServerProps,
isNextImageImported,
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return {}
......
......@@ -3,6 +3,10 @@ import Head from '../next-server/lib/head'
import { toBase64 } from '../next-server/lib/to-base-64'
import { useIntersection } from './use-intersection'
if (typeof window === 'undefined') {
;(global as any).__NEXT_IMAGE_IMPORTED = true
}
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number]
......
......@@ -23,6 +23,7 @@ import {
CLIENT_STATIC_FILES_PATH,
CONFIG_FILE,
EXPORT_DETAIL,
EXPORT_MARKER,
PAGES_MANIFEST,
PHASE_EXPORT,
PRERENDER_MANIFEST,
......@@ -283,7 +284,10 @@ export default async function exportApp(
}
}
const { i18n } = nextConfig
const {
i18n,
images: { loader = 'default' },
} = nextConfig
if (i18n && !options.buildExport) {
throw new Error(
......@@ -291,6 +295,27 @@ export default async function exportApp(
)
}
const { isNextImageImported } = await promises
.readFile(join(distDir, EXPORT_MARKER), 'utf8')
.then((text) => JSON.parse(text))
.catch(() => ({}))
if (
isNextImageImported &&
loader === 'default' &&
!options.buildExport &&
!hasNextSupport
) {
throw new Error(
`Image Optimization using Next.js' default loader is not compatible with \`next export\`.
Possible solutions:
- Use \`next start\`, which starts the Image Optimization API.
- Use Vercel to deploy, which supports Image Optimization.
- Configure a third-party loader in \`next.config.js\`.
Read more: https://err.sh/next.js/export-image-api`
)
}
// Start the rendering process
const renderOpts = {
dir,
......
import Image from 'next/image'
export default () => (
<div>
<p>Should error during export</p>
<Image src="/i.png" width="10" height="10" />
</div>
)
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
jest.setTimeout(1000 * 60 * 5)
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export with default loader next/image component', () => {
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 have error during next export', async () => {
const { stderr } = await nextExport(appDir, { outdir }, { stderr: true })
expect(stderr).toContain(
"Image Optimization using Next.js' default loader is not compatible with `next export`."
)
})
})
module.exports = {
images: {
loader: 'cloudinary',
path: 'https://example.com/',
},
}
import Image from 'next/image'
export default () => (
<div>
<p>Should succeed during export</p>
<Image alt="icon" src="/i.png" width="10" height="10" />
</div>
)
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport } from 'next-test-utils'
jest.setTimeout(1000 * 60 * 5)
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export with cloudinary loader next/image component', () => {
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')
})
})
......@@ -30,6 +30,7 @@ describe('Application Export Intent Output', () => {
Object {
"exportTrailingSlash": false,
"hasExportPathMap": false,
"isNextImageImported": false,
"version": 1,
}
`)
......@@ -70,6 +71,7 @@ describe('Application Export Intent Output', () => {
Object {
"exportTrailingSlash": false,
"hasExportPathMap": true,
"isNextImageImported": false,
"version": 1,
}
`)
......@@ -110,6 +112,7 @@ describe('Application Export Intent Output', () => {
Object {
"exportTrailingSlash": true,
"hasExportPathMap": false,
"isNextImageImported": false,
"version": 1,
}
`)
......@@ -150,6 +153,7 @@ describe('Application Export Intent Output', () => {
Object {
"exportTrailingSlash": false,
"hasExportPathMap": false,
"isNextImageImported": false,
"version": 1,
}
`)
......@@ -189,6 +193,7 @@ describe('Application Export Intent Output', () => {
Object {
"exportTrailingSlash": false,
"hasExportPathMap": false,
"isNextImageImported": false,
"version": 1,
}
`)
......
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