Unverified Commit 6773ea86 authored by Steven's avatar Steven Committed by GitHub

fix: improve error message when `output: export` in app router (#54202)

There are a few cases that are not handled by App Router when using `output: export` config.

A few of them are expected, but some are yet to be implemented. Regardless of the intent of the future, this PR ensures the error messages match what was documented to be [unsupported](https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features).

- Documentation: https://github.com/vercel/next.js/pull/53592
- Issue: #48022 
parent 0718aec9
......@@ -43,6 +43,7 @@ export interface PageStaticInfo {
ssg?: boolean
ssr?: boolean
rsc?: RSCModuleType
generateStaticParams?: boolean
middleware?: MiddlewareConfig
amp?: boolean | 'hybrid'
extraConfig?: Record<string, any>
......@@ -74,7 +75,15 @@ export function getRSCModuleInformation(
const clientEntryType = clientInfoMatch?.[2] as 'cjs' | 'auto'
const type = clientRefs ? RSC_MODULE_TYPES.client : RSC_MODULE_TYPES.server
return { type, actions, clientRefs, clientEntryType, isClientRef }
const hasUseClientDirective = /^\s*['"]use client['"]/.test(source)
return {
type,
actions,
clientRefs,
clientEntryType,
isClientRef,
hasUseClientDirective,
}
}
const warnedInvalidValueMap = {
......@@ -113,6 +122,7 @@ function checkExports(
preferredRegion?: string | string[]
generateImageMetadata?: boolean
generateSitemaps?: boolean
generateStaticParams: boolean
extraProperties?: Set<string>
} {
const exportsSet = new Set<string>([
......@@ -120,6 +130,7 @@ function checkExports(
'getServerSideProps',
'generateImageMetadata',
'generateSitemaps',
'generateStaticParams',
])
if (Array.isArray(swcAST?.body)) {
try {
......@@ -129,6 +140,7 @@ function checkExports(
let ssg: boolean = false
let generateImageMetadata: boolean = false
let generateSitemaps: boolean = false
let generateStaticParams = false
let extraProperties = new Set<string>()
for (const node of swcAST.body) {
......@@ -169,6 +181,7 @@ function checkExports(
ssr = id === 'getServerSideProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
generateStaticParams = id === 'generateStaticParams'
}
if (
......@@ -181,6 +194,7 @@ function checkExports(
ssr = id === 'getServerSideProps'
generateImageMetadata = id === 'generateImageMetadata'
generateSitemaps = id === 'generateSitemaps'
generateStaticParams = id === 'generateStaticParams'
}
}
......@@ -199,6 +213,8 @@ function checkExports(
generateImageMetadata = true
if (!generateSitemaps && value === 'generateSitemaps')
generateSitemaps = true
if (!generateStaticParams && value === 'generateStaticParams')
generateStaticParams = true
if (!runtime && value === 'runtime')
warnInvalidValue(
pageFilePath,
......@@ -222,6 +238,7 @@ function checkExports(
preferredRegion,
generateImageMetadata,
generateSitemaps,
generateStaticParams,
extraProperties,
}
} catch (err) {}
......@@ -234,6 +251,7 @@ function checkExports(
preferredRegion: undefined,
generateImageMetadata: false,
generateSitemaps: false,
generateStaticParams: false,
extraProperties: undefined,
}
}
......@@ -437,14 +455,21 @@ export async function getPageStaticInfo(params: {
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if (
/runtime|preferredRegion|getStaticProps|getServerSideProps|export const/.test(
/runtime|preferredRegion|getStaticProps|getServerSideProps|generateStaticParams|export const/.test(
fileContent
)
) {
const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr, runtime, preferredRegion, extraProperties } =
checkExports(swcAST, pageFilePath)
const rsc = getRSCModuleInformation(fileContent).type
const {
ssg,
ssr,
runtime,
preferredRegion,
generateStaticParams,
extraProperties,
} = checkExports(swcAST, pageFilePath)
const rscInfo = getRSCModuleInformation(fileContent)
const rsc = rscInfo.type
// default / failsafe value for config
let config: any
......@@ -548,10 +573,21 @@ export async function getPageStaticInfo(params: {
nextConfig
)
if (
pageType === 'app' &&
rscInfo.hasUseClientDirective &&
generateStaticParams
) {
throw new Error(
`Page "${page}" cannot use both "use client" and export function "generateStaticParams()".`
)
}
return {
ssr,
ssg,
rsc,
generateStaticParams,
amp: config.amp || false,
...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }),
......@@ -564,6 +600,7 @@ export async function getPageStaticInfo(params: {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
generateStaticParams: false,
amp: false,
runtime: undefined,
}
......
......@@ -1612,6 +1612,16 @@ export default async function build(
const hasGenerateStaticParams =
!!workerResult.prerenderRoutes?.length
if (
config.output === 'export' &&
isDynamic &&
!hasGenerateStaticParams
) {
throw new Error(
`Page "${page}" is missing "generateStaticParams()" so it cannot be used with "output: export" config.`
)
}
if (
// Mark the app as static if:
// - It has no dynamic param
......
......@@ -1138,25 +1138,31 @@ export const collectGenerateParams = async (
? segment[2]?.layout?.[0]?.()
: segment[2]?.page?.[0]?.())
const config = collectAppConfig(mod)
const page: string | undefined = segment[0]
const isClientComponent = isClientReference(mod)
const isDynamicSegment = segment[0] && /^\[.+\]$/.test(segment[0])
const isDynamicSegment = /^\[.+\]$/.test(page || '')
const { generateStaticParams, getStaticPaths } = mod || {}
//console.log({parentSegments, page, isDynamicSegment, isClientComponent, generateStaticParams})
if (isDynamicSegment && isClientComponent && generateStaticParams) {
throw new Error(
`Page "${page}" cannot export "generateStaticParams()" because it is a client component`
)
}
const result = {
isLayout,
isDynamicSegment,
segmentPath: `/${parentSegments.join('/')}${
segment[0] && parentSegments.length > 0 ? '/' : ''
}${segment[0]}`,
page && parentSegments.length > 0 ? '/' : ''
}${page}`,
config,
getStaticPaths: isClientComponent ? undefined : mod?.getStaticPaths,
generateStaticParams: isClientComponent
? undefined
: mod?.generateStaticParams,
getStaticPaths: isClientComponent ? undefined : getStaticPaths,
generateStaticParams: isClientComponent ? undefined : generateStaticParams,
}
if (segment[0]) {
parentSegments.push(segment[0])
if (page) {
parentSegments.push(page)
}
if (result.config || result.generateStaticParams || result.getStaticPaths) {
......
......@@ -32,6 +32,7 @@ export interface RSCMeta {
clientRefs?: string[]
clientEntryType?: 'cjs' | 'auto'
isClientRef?: boolean
hasUseClientDirective?: boolean
requests?: string[] // client requests in flight client entry
}
......
......@@ -1456,6 +1456,24 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const hasFallback = typeof fallbackMode !== 'undefined'
if (this.nextConfig.output === 'export') {
const page = components.pathname
const isDynamic = isDynamicRoute(page)
if (isDynamic) {
if (fallbackMode !== 'static') {
throw new Error(
`Page "${page}" is missing exported function "generateStaticParams()", which is required with "output: export" config.`
)
}
const resolvedWithoutSlash = removeTrailingSlash(resolvedUrlPathname)
if (!staticPaths?.includes(resolvedWithoutSlash)) {
throw new Error(
`Page "${page}" is missing param "${resolvedWithoutSlash}" in "generateStaticParams()", which is required with "output: export" config.`
)
}
}
}
if (hasFallback) {
hasStaticPaths = true
}
......
'use client'
export const dynamic = 'force-static'
export function generateStaticParams() {
return [{ slug: 'use client should not fail build' }]
}
export default function Page({ params }) {
return (
<main>
<h1>Use Client Example</h1>
<p>{params.slug}</p>
</main>
)
}
'use client'
export default function Page() {
return (
<main>
<h1>Use Client Example</h1>
</main>
)
}
import { runTests } from './utils'
it('should error when dynamic route is missing generateStaticParams', async () => {
await runTests({
isDev: true,
dynamicPage: 'undefined',
generateStaticParamsOpt: 'set noop',
expectedErrMsg:
'Page "/another/[slug]/page" is missing exported function "generateStaticParams()", which is required with "output: export" config.',
})
})
it('should error when client component has generateStaticParams', async () => {
await runTests({
isDev: true,
dynamicPage: 'undefined',
generateStaticParamsOpt: 'set client',
expectedErrMsg:
'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".',
})
})
import { runTests } from './utils'
it('should error when dynamic route is missing generateStaticParams', async () => {
await runTests({
isDev: false,
dynamicPage: 'undefined',
generateStaticParamsOpt: 'set noop',
expectedErrMsg:
'Page "/another/[slug]" is missing "generateStaticParams()" so it cannot be used with "output: export" config.',
})
})
it('should error when client component has generateStaticParams', async () => {
await runTests({
isDev: false,
dynamicPage: 'undefined',
generateStaticParamsOpt: 'set client',
expectedErrMsg:
'Page "/another/[slug]/page" cannot use both "use client" and export function "generateStaticParams()".',
})
})
......@@ -41,6 +41,8 @@ export const expectedWhenTrailingSlashTrue = [
'another/second/index.txt',
'api/json',
'api/txt',
'client/index.html',
'client/index.txt',
'favicon.ico',
'image-import/index.html',
'image-import/index.txt',
......@@ -62,6 +64,8 @@ const expectedWhenTrailingSlashFalse = [
'another/second.txt',
'api/json',
'api/txt',
'client.html',
'client.txt',
'favicon.ico',
'image-import.html',
'image-import.txt',
......@@ -87,12 +91,14 @@ export async function runTests({
trailingSlash = true,
dynamicPage,
dynamicApiRoute,
generateStaticParamsOpt,
expectedErrMsg,
}: {
isDev?: boolean
trailingSlash?: boolean
dynamicPage?: string
dynamicApiRoute?: string
generateStaticParamsOpt?: 'set noop' | 'set client'
expectedErrMsg?: string
}) {
if (trailingSlash !== undefined) {
......@@ -113,6 +119,11 @@ export async function runTests({
`const dynamic = ${dynamicApiRoute}`
)
}
if (generateStaticParamsOpt === 'set noop') {
slugPage.replace('export function generateStaticParams', 'function noop')
} else if (generateStaticParamsOpt === 'set client') {
slugPage.prepend('"use client"\n')
}
await fs.remove(distDir)
await fs.remove(exportDir)
const port = await findPort()
......
......@@ -688,6 +688,11 @@ export class File {
this.write(newContent)
}
prepend(str: string) {
const content = readFileSync(this.path, 'utf8')
this.write(str + content)
}
delete() {
unlinkSync(this.path)
}
......
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