Unverified Commit 25efdfad authored by Steven's avatar Steven Committed by GitHub

Add support for `output: export` config (#46744)

## Background

In the early days, `next export` was created when Next.js was SSR-only in order to statically export your pages for self hosting where no server was available. However, around the time `getStaticProps()` and `getStaticPaths()` were introduced, Next.js began [automatically generating static pages](https://nextjs.org/docs/advanced-features/automatic-static-optimization) (SSG first and SSR opt-in) during `next build`. This meant there were very few reasons to use `next export` and it started to become a stale feature.

## Problem We Need To Solve

Users targeting `next export` currently have a really bad experience. They start a new project and use all the features Next.js has to offer because they all features work with `next dev`. Then when development is finished and it comes time to deploy, running `next build && next export` will fail with errors for [unsupported features](https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features).

## Solution

This PR introduces a new configuration option, `output: 'export'`, to indicate that the user intends to run `next export`.

With this change, Next.js can fail fast during `next dev` if any [unsupported features](https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features) are used, thereby improving developer experience with instant feedback.


```js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  output: 'export',
}

module.exports = nextConfig
```
parent ef685e8f
...@@ -17,7 +17,20 @@ If you're looking to build a hybrid site where only _some_ pages are prerendered ...@@ -17,7 +17,20 @@ If you're looking to build a hybrid site where only _some_ pages are prerendered
## `next export` ## `next export`
Update your build script in `package.json` to use `next export`: Update your `next.config.js` file to include `output: "export"` like the following:
```js
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'export',
}
module.exports = nextConfig
```
Update your scripts in `package.json` file to include `next export` like the following:
```json ```json
"scripts": { "scripts": {
...@@ -59,7 +72,8 @@ Features that require a Node.js server, or dynamic logic that cannot be computed ...@@ -59,7 +72,8 @@ Features that require a Node.js server, or dynamic logic that cannot be computed
- [Headers](/docs/api-reference/next.config.js/headers.md) - [Headers](/docs/api-reference/next.config.js/headers.md)
- [Middleware](/docs/middleware.md) - [Middleware](/docs/middleware.md)
- [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) - [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md)
- [`fallback: true`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-true) - [`getStaticPaths` with `fallback: true`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-true)
- [`getStaticPaths` with `fallback: 'blocking'`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-blocking)
- [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) - [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)
### `getInitialProps` ### `getInitialProps`
......
...@@ -313,6 +313,7 @@ export function getDefineEnv({ ...@@ -313,6 +313,7 @@ export function getDefineEnv({
// 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,
remotePatterns: config.images?.remotePatterns, remotePatterns: config.images?.remotePatterns,
output: config.output,
} }
: {}), : {}),
}), }),
......
...@@ -35,7 +35,10 @@ if (typeof window === 'undefined') { ...@@ -35,7 +35,10 @@ 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]
type ImageConfig = ImageConfigComplete & { allSizes: number[] } type ImageConfig = ImageConfigComplete & {
allSizes: number[]
output?: 'standalone' | 'export'
}
export type { ImageLoaderProps } export type { ImageLoaderProps }
export type ImageLoader = (p: ImageLoaderProps) => string export type ImageLoader = (p: ImageLoaderProps) => string
...@@ -645,6 +648,15 @@ const Image = forwardRef<HTMLImageElement | null, ImageProps>( ...@@ -645,6 +648,15 @@ const Image = forwardRef<HTMLImageElement | null, ImageProps>(
const qualityInt = getInt(quality) const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (config.output === 'export' && isDefaultLoader && !unoptimized) {
throw new Error(
`Image Optimization using Next.js' default loader is not compatible with \`{ output: "export" }\`.
Possible solutions:
- Configure \`{ output: "standalone" }\` or remove it to run server mode including the Image Optimization API.
- Configure \`{ images: { unoptimized: true } }\` in \`next.config.js\` to disable the Image Optimization API.
Read more: https://nextjs.org/docs/messages/export-image-api`
)
}
if (!src) { if (!src) {
// React doesn't show the stack trace and there's // React doesn't show the stack trace and there's
// no `src` to help identify which image, so we // no `src` to help identify which image, so we
......
...@@ -401,6 +401,7 @@ export default async function exportApp( ...@@ -401,6 +401,7 @@ export default async function exportApp(
runtime: nextConfig.experimental.runtime, runtime: nextConfig.experimental.runtime,
crossOrigin: nextConfig.crossOrigin, crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers, nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts as FontConfig, optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes, largePageDataBytes: nextConfig.experimental.largePageDataBytes,
......
...@@ -215,6 +215,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -215,6 +215,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
fontManifest?: FontManifest fontManifest?: FontManifest
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
optimizeCss: any optimizeCss: any
nextConfigOutput: 'standalone' | 'export'
nextScriptWorkers: any nextScriptWorkers: any
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -409,6 +410,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -409,6 +410,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
? this.getFontManifest() ? this.getFontManifest()
: undefined, : undefined,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
nextConfigOutput: this.nextConfig.output,
nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers, nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,
disableOptimizedLoading: this.nextConfig.experimental.runtime disableOptimizedLoading: this.nextConfig.experimental.runtime
? true ? true
......
...@@ -704,7 +704,7 @@ const configSchema = { ...@@ -704,7 +704,7 @@ const configSchema = {
}, },
output: { output: {
// automatic typing doesn't like enum // automatic typing doesn't like enum
enum: ['standalone'] as any, enum: ['standalone', 'export'] as any,
type: 'string', type: 'string',
}, },
outputFileTracing: { outputFileTracing: {
......
...@@ -544,7 +544,7 @@ export interface NextConfig extends Record<string, any> { ...@@ -544,7 +544,7 @@ export interface NextConfig extends Record<string, any> {
} }
} }
output?: 'standalone' output?: 'standalone' | 'export'
// A list of packages that should always be transpiled and bundled in the server // A list of packages that should always be transpiled and bundled in the server
transpilePackages?: string[] transpilePackages?: string[]
......
...@@ -260,6 +260,29 @@ function assignDefaults( ...@@ -260,6 +260,29 @@ function assignDefaults(
const result = { ...defaultConfig, ...config } const result = { ...defaultConfig, ...config }
if (result.output === 'export') {
if (result.i18n) {
throw new Error(
'Specified "i18n" cannot but used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
if (result.rewrites) {
throw new Error(
'Specified "rewrites" cannot but used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
if (result.redirects) {
throw new Error(
'Specified "redirects" cannot but used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
if (result.headers) {
throw new Error(
'Specified "headers" cannot but used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
}
if (typeof result.assetPrefix !== 'string') { if (typeof result.assetPrefix !== 'string') {
throw new Error( throw new Error(
`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://nextjs.org/docs/messages/invalid-assetprefix` `Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://nextjs.org/docs/messages/invalid-assetprefix`
......
...@@ -489,6 +489,12 @@ export default class DevServer extends Server { ...@@ -489,6 +489,12 @@ export default class DevServer extends Server {
}) })
if (isMiddlewareFile(rootFile)) { if (isMiddlewareFile(rootFile)) {
if (this.nextConfig.output === 'export') {
Log.error(
'Middleware cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
continue
}
this.actualMiddlewareFile = rootFile this.actualMiddlewareFile = rootFile
middlewareMatchers = staticInfo.middleware?.matchers || [ middlewareMatchers = staticInfo.middleware?.matchers || [
{ regexp: '.*' }, { regexp: '.*' },
...@@ -513,6 +519,16 @@ export default class DevServer extends Server { ...@@ -513,6 +519,16 @@ export default class DevServer extends Server {
keepIndex: isAppPath, keepIndex: isAppPath,
}) })
if (
pageName.startsWith('/api/') &&
this.nextConfig.output === 'export'
) {
Log.error(
'API Routes cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
continue
}
if (isAppPath) { if (isAppPath) {
if (!isLayoutsLeafPage(fileName, this.nextConfig.pageExtensions)) { if (!isLayoutsLeafPage(fileName, this.nextConfig.pageExtensions)) {
continue continue
...@@ -1536,6 +1552,18 @@ export default class DevServer extends Server { ...@@ -1536,6 +1552,18 @@ export default class DevServer extends Server {
await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, []) await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, [])
).value ).value
if (this.nextConfig.output === 'export') {
if (fallback === 'blocking') {
throw new Error(
'getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
} else if (fallback === true) {
throw new Error(
'getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
}
return { return {
staticPaths, staticPaths,
fallbackMode: fallbackMode:
......
...@@ -404,7 +404,7 @@ export async function optimizeImage({ ...@@ -404,7 +404,7 @@ export async function optimizeImage({
quality: number quality: number
width: number width: number
height?: number height?: number
nextConfigOutput?: 'standalone' nextConfigOutput?: 'standalone' | 'export'
}): Promise<Buffer> { }): Promise<Buffer> {
let optimizedBuffer = buffer let optimizedBuffer = buffer
if (sharp) { if (sharp) {
...@@ -449,7 +449,7 @@ export async function optimizeImage({ ...@@ -449,7 +449,7 @@ export async function optimizeImage({
optimizedBuffer = await transformer.toBuffer() optimizedBuffer = await transformer.toBuffer()
// End sharp transformation logic // End sharp transformation logic
} else { } else {
if (showSharpMissingWarning && nextConfigOutput) { if (showSharpMissingWarning && nextConfigOutput === 'standalone') {
// TODO: should we ensure squoosh also works even though we don't // TODO: should we ensure squoosh also works even though we don't
// recommend it be used in production and this is a production feature // recommend it be used in production and this is a production feature
console.error( console.error(
......
...@@ -391,7 +391,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -391,7 +391,7 @@ export default class NextNodeServer extends BaseServer {
type: 'route', type: 'route',
name: '_next/image catchall', name: '_next/image catchall',
fn: async (req, res, _params, parsedUrl) => { fn: async (req, res, _params, parsedUrl) => {
if (this.minimalMode) { if (this.minimalMode || this.nextConfig.output === 'export') {
res.statusCode = 400 res.statusCode = 400
res.body('Bad Request').send() res.body('Bad Request').send()
return { return {
...@@ -1235,6 +1235,10 @@ export default class NextNodeServer extends BaseServer { ...@@ -1235,6 +1235,10 @@ export default class NextNodeServer extends BaseServer {
const edgeFunctionsPages = this.getEdgeFunctionsPages() const edgeFunctionsPages = this.getEdgeFunctionsPages()
for (const edgeFunctionsPage of edgeFunctionsPages) { for (const edgeFunctionsPage of edgeFunctionsPages) {
if (edgeFunctionsPage === match.definition.page) { if (edgeFunctionsPage === match.definition.page) {
if (this.nextConfig.output === 'export') {
await this.render404(req, res, parsedUrl)
return { finished: true }
}
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
const handledAsEdgeFunction = await this.runEdgeFunction({ const handledAsEdgeFunction = await this.runEdgeFunction({
...@@ -1257,6 +1261,10 @@ export default class NextNodeServer extends BaseServer { ...@@ -1257,6 +1261,10 @@ export default class NextNodeServer extends BaseServer {
// it. // it.
// TODO: move this behavior into a route handler. // TODO: move this behavior into a route handler.
if (match.definition.kind === RouteKind.PAGES_API) { if (match.definition.kind === RouteKind.PAGES_API) {
if (this.nextConfig.output === 'export') {
await this.render404(req, res, parsedUrl)
return { finished: true }
}
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
handled = await this.handleApiRequest( handled = await this.handleApiRequest(
......
...@@ -241,6 +241,7 @@ export type RenderOptsPartial = { ...@@ -241,6 +241,7 @@ export type RenderOptsPartial = {
optimizeFonts: FontConfig optimizeFonts: FontConfig
fontManifest?: FontManifest fontManifest?: FontManifest
optimizeCss: any optimizeCss: any
nextConfigOutput?: 'standalone' | 'export'
nextScriptWorkers: any nextScriptWorkers: any
devOnlyCacheBusterQueryString?: string devOnlyCacheBusterQueryString?: string
resolvedUrl?: string resolvedUrl?: string
...@@ -467,6 +468,12 @@ export async function renderToHTML( ...@@ -467,6 +468,12 @@ export async function renderToHTML(
throw new Error(SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`) throw new Error(SERVER_PROPS_SSG_CONFLICT + ` ${pathname}`)
} }
if (getServerSideProps && renderOpts.nextConfigOutput === 'export') {
throw new Error(
'getServerSideProps cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
if (getStaticPaths && !pageIsDynamic) { if (getStaticPaths && !pageIsDynamic) {
throw new Error( throw new Error(
`getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` + `getStaticPaths is only allowed for dynamic SSG pages and was found on '${pathname}'.` +
...@@ -846,6 +853,11 @@ export async function renderToHTML( ...@@ -846,6 +853,11 @@ export async function renderToHTML(
} }
if ('revalidate' in data) { if ('revalidate' in data) {
if (data.revalidate && renderOpts.nextConfigOutput === 'export') {
throw new Error(
'ISR cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
)
}
if (typeof data.revalidate === 'number') { if (typeof data.revalidate === 'number') {
if (!Number.isInteger(data.revalidate)) { if (!Number.isInteger(data.revalidate)) {
throw new Error( throw new Error(
...@@ -1400,6 +1412,7 @@ export async function renderToHTML( ...@@ -1400,6 +1412,7 @@ export async function renderToHTML(
crossOrigin: renderOpts.crossOrigin, crossOrigin: renderOpts.crossOrigin,
optimizeCss: renderOpts.optimizeCss, optimizeCss: renderOpts.optimizeCss,
optimizeFonts: renderOpts.optimizeFonts, optimizeFonts: renderOpts.optimizeFonts,
nextConfigOutput: renderOpts.nextConfigOutput,
nextScriptWorkers: renderOpts.nextScriptWorkers, nextScriptWorkers: renderOpts.nextScriptWorkers,
runtime: globalRuntime, runtime: globalRuntime,
largePageDataBytes: renderOpts.largePageDataBytes, largePageDataBytes: renderOpts.largePageDataBytes,
......
...@@ -39,6 +39,7 @@ export type HtmlProps = { ...@@ -39,6 +39,7 @@ export type HtmlProps = {
crossOrigin?: string crossOrigin?: string
optimizeCss?: any optimizeCss?: any
optimizeFonts?: FontConfig optimizeFonts?: FontConfig
nextConfigOutput?: 'standalone' | 'export'
nextScriptWorkers?: boolean nextScriptWorkers?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
hasConcurrentFeatures?: boolean hasConcurrentFeatures?: boolean
......
// prettier-ignore
module.exports = {
output: 'export',
}
This diff is collapsed.
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<h1>Export Config</h1>
<p>This page should error since you can't export images</p>
<Image id="i" alt="i" src="/test.webp" width={200} height={200} />
</div>
)
}
export default Page
/* eslint-env jest */
import { join } from 'path'
import {
findPort,
getRedboxHeader,
hasRedbox,
killApp,
launchApp,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../')
let appPort
let app
let stderr = ''
describe('next/image with output export config', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg || ''
},
})
})
afterAll(async () => {
await killApp(app)
stderr = ''
})
it('should error', async () => {
const browser = await webdriver(appPort, '/')
const msg =
'Image Optimization using Next.js\' default loader is not compatible with `{ output: "export" }`.'
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxHeader(browser)).toContain(msg)
expect(stderr).toContain(msg)
})
})
})
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