Unverified Commit b590ec39 authored by Steven's avatar Steven Committed by GitHub

feat: add `output: export` support for `appDir` (#47022)

We can now support `next export` for `appDir` because of the new config added in #46744.
fixes NEXT-775 ([NEXT-775](https://linear.app/vercel/issue/NEXT-775))
parent c27b5469
...@@ -1282,6 +1282,7 @@ export default async function build( ...@@ -1282,6 +1282,7 @@ export default async function build(
enableUndici: config.experimental.enableUndici, enableUndici: config.experimental.enableUndici,
locales: config.i18n?.locales, locales: config.i18n?.locales,
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output,
}) })
) )
...@@ -1466,6 +1467,7 @@ export default async function build( ...@@ -1466,6 +1467,7 @@ export default async function build(
isrFlushToDisk: config.experimental.isrFlushToDisk, isrFlushToDisk: config.experimental.isrFlushToDisk,
maxMemoryCacheSize: maxMemoryCacheSize:
config.experimental.isrMemoryCacheSize, config.experimental.isrMemoryCacheSize,
nextConfigOutput: config.output,
}) })
} }
) )
......
...@@ -1329,6 +1329,7 @@ export async function isPageStatic({ ...@@ -1329,6 +1329,7 @@ export async function isPageStatic({
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
incrementalCacheHandlerPath, incrementalCacheHandlerPath,
nextConfigOutput,
}: { }: {
page: string page: string
distDir: string distDir: string
...@@ -1347,6 +1348,7 @@ export async function isPageStatic({ ...@@ -1347,6 +1348,7 @@ export async function isPageStatic({
isrFlushToDisk?: boolean isrFlushToDisk?: boolean
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
incrementalCacheHandlerPath?: string incrementalCacheHandlerPath?: string
nextConfigOutput: 'standalone' | 'export'
}): Promise<{ }): Promise<{
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
...@@ -1480,6 +1482,16 @@ export async function isPageStatic({ ...@@ -1480,6 +1482,16 @@ export async function isPageStatic({
{} {}
) )
if (nextConfigOutput === 'export') {
if (!appConfig.dynamic || appConfig.dynamic === 'auto') {
appConfig.dynamic = 'error'
} else if (appConfig.dynamic === 'force-dynamic') {
throw new Error(
`export const dynamic = "force-dynamic" on page "${page}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`
)
}
}
if (appConfig.dynamic === 'force-dynamic') { if (appConfig.dynamic === 'force-dynamic') {
appConfig.revalidate = 0 appConfig.revalidate = 0
} }
......
...@@ -319,6 +319,7 @@ export function getDefineEnv({ ...@@ -319,6 +319,7 @@ export function getDefineEnv({
}), }),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath), 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites), 'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
'process.env.__NEXT_CONFIG_OUTPUT': JSON.stringify(config.output),
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n), 'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains), 'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId), 'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
......
...@@ -35,7 +35,16 @@ export async function fetchServerResponse( ...@@ -35,7 +35,16 @@ export async function fetchServerResponse(
} }
try { try {
const res = await fetch(url.toString(), { let fetchUrl = url
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
fetchUrl = new URL(url) // clone
if (fetchUrl.pathname.endsWith('/')) {
fetchUrl.pathname += 'index.txt'
} else {
fetchUrl.pathname += '.txt'
}
}
const res = await fetch(fetchUrl, {
// Backwards compat for older browsers. `same-origin` is the default in modern browsers. // Backwards compat for older browsers. `same-origin` is the default in modern browsers.
credentials: 'same-origin', credentials: 'same-origin',
headers, headers,
...@@ -44,8 +53,14 @@ export async function fetchServerResponse( ...@@ -44,8 +53,14 @@ export async function fetchServerResponse(
? urlToUrlWithoutFlightMarker(res.url) ? urlToUrlWithoutFlightMarker(res.url)
: undefined : undefined
const isFlightResponse = const contentType = res.headers.get('content-type') || ''
res.headers.get('content-type') === RSC_CONTENT_TYPE_HEADER let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
if (!isFlightResponse) {
isFlightResponse = contentType.startsWith('text/plain')
}
}
// If fetch returns something different than flight response handle it like a mpa navigation // If fetch returns something different than flight response handle it like a mpa navigation
if (!isFlightResponse) { if (!isFlightResponse) {
......
...@@ -31,6 +31,7 @@ import { ...@@ -31,6 +31,7 @@ import {
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import loadConfig from '../server/config' import loadConfig from '../server/config'
import { ExportPathMap, NextConfigComplete } from '../server/config-shared' import { ExportPathMap, NextConfigComplete } from '../server/config-shared'
...@@ -51,6 +52,9 @@ import { ...@@ -51,6 +52,9 @@ import {
overrideBuiltInReactPackages, overrideBuiltInReactPackages,
} from '../build/webpack/require-hook' } from '../build/webpack/require-hook'
import { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route'
import isError from '../lib/is-error'
loadRequireHook() loadRequireHook()
if (process.env.NEXT_PREBUNDLED_REACT) { if (process.env.NEXT_PREBUNDLED_REACT) {
...@@ -238,6 +242,23 @@ export default async function exportApp( ...@@ -238,6 +242,23 @@ export default async function exportApp(
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST)) prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
} catch (_) {} } catch (_) {}
let appRoutePathManifest: Record<string, string> | undefined = undefined
try {
appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST))
} catch (err) {
if (
isError(err) &&
(err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND')
) {
// the manifest doesn't exist which will happen when using
// "pages" dir instead of "app" dir.
appRoutePathManifest = undefined
} else {
// the manifest is malformed (invalid json)
throw err
}
}
const excludedPrerenderRoutes = new Set<string>() const excludedPrerenderRoutes = new Set<string>()
const pages = options.pages || Object.keys(pagesManifest) const pages = options.pages || Object.keys(pagesManifest)
const defaultPathMap: ExportPathMap = {} const defaultPathMap: ExportPathMap = {}
...@@ -269,6 +290,25 @@ export default async function exportApp( ...@@ -269,6 +290,25 @@ export default async function exportApp(
defaultPathMap[page] = { page } defaultPathMap[page] = { page }
} }
const mapAppRouteToPage = new Map<string, string>()
if (!options.buildExport && appRoutePathManifest) {
for (const [pageName, routePath] of Object.entries(
appRoutePathManifest
)) {
mapAppRouteToPage.set(routePath, pageName)
if (
isAppPageRoute(pageName) &&
!prerenderManifest?.routes[routePath] &&
!prerenderManifest?.dynamicRoutes[routePath]
) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true,
}
}
}
}
// Initialize the output directory // Initialize the output directory
const outDir = options.outdir const outDir = options.outdir
...@@ -711,7 +751,10 @@ export default async function exportApp( ...@@ -711,7 +751,10 @@ export default async function exportApp(
await Promise.all( await Promise.all(
Object.keys(prerenderManifest.routes).map(async (route) => { Object.keys(prerenderManifest.routes).map(async (route) => {
const { srcRoute } = prerenderManifest!.routes[route] const { srcRoute } = prerenderManifest!.routes[route]
const pageName = srcRoute || route const appPageName = mapAppRouteToPage.get(srcRoute || '')
const pageName = appPageName || srcRoute || route
const isAppPath = Boolean(appPageName)
const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName)
// returning notFound: true from getStaticProps will not // returning notFound: true from getStaticProps will not
// output html/json files during the build // output html/json files during the build
...@@ -720,7 +763,7 @@ export default async function exportApp( ...@@ -720,7 +763,7 @@ export default async function exportApp(
} }
route = normalizePagePath(route) route = normalizePagePath(route)
const pagePath = getPagePath(pageName, distDir, undefined, false) const pagePath = getPagePath(pageName, distDir, undefined, isAppPath)
const distPagesDir = join( const distPagesDir = join(
pagePath, pagePath,
// strip leading / and then recurse number of nested dirs // strip leading / and then recurse number of nested dirs
...@@ -733,6 +776,15 @@ export default async function exportApp( ...@@ -733,6 +776,15 @@ export default async function exportApp(
) )
const orig = join(distPagesDir, route) const orig = join(distPagesDir, route)
const handlerSrc = `${orig}.body`
const handlerDest = join(outDir, route)
if (isAppRouteHandler && (await exists(handlerSrc))) {
await promises.mkdir(dirname(handlerDest), { recursive: true })
await promises.copyFile(handlerSrc, handlerDest)
return
}
const htmlDest = join( const htmlDest = join(
outDir, outDir,
`${route}${ `${route}${
...@@ -743,13 +795,20 @@ export default async function exportApp( ...@@ -743,13 +795,20 @@ export default async function exportApp(
outDir, outDir,
`${route}.amp${subFolders ? `${sep}index` : ''}.html` `${route}.amp${subFolders ? `${sep}index` : ''}.html`
) )
const jsonDest = join(pagesDataDir, `${route}.json`) const jsonDest = isAppPath
? join(
outDir,
`${route}${
subFolders && route !== '/index' ? `${sep}index` : ''
}.txt`
)
: join(pagesDataDir, `${route}.json`)
await promises.mkdir(dirname(htmlDest), { recursive: true }) await promises.mkdir(dirname(htmlDest), { recursive: true })
await promises.mkdir(dirname(jsonDest), { recursive: true }) await promises.mkdir(dirname(jsonDest), { recursive: true })
const htmlSrc = `${orig}.html` const htmlSrc = `${orig}.html`
const jsonSrc = `${orig}.json` const jsonSrc = `${orig}${isAppPath ? '.rsc' : '.json'}`
await promises.copyFile(htmlSrc, htmlDest) await promises.copyFile(htmlSrc, htmlDest)
await promises.copyFile(jsonSrc, jsonDest) await promises.copyFile(jsonSrc, jsonDest)
......
...@@ -240,7 +240,11 @@ export interface ExperimentalConfig { ...@@ -240,7 +240,11 @@ export interface ExperimentalConfig {
} }
export type ExportPathMap = { export type ExportPathMap = {
[path: string]: { page: string; query?: Record<string, string | string[]> } [path: string]: {
page: string
query?: Record<string, string | string[]>
_isAppDir?: boolean
}
} }
/** /**
......
import Link from 'next/link'
export const dynamic = 'force-static'
export function generateStaticParams() {
return [{ slug: 'first' }, { slug: 'second' }]
}
export default function Page({ params }) {
return (
<main>
<h1>{params.slug}</h1>
<ul>
<li>
<Link href="/another">Visit another page</Link>
</li>
</ul>
</main>
)
}
import Link from 'next/link'
export default function Another() {
return (
<main>
<h1>Another</h1>
<ul>
<li>
<Link href="/">Visit the home page</Link>
</li>
<li>
<Link href="/another">another page</Link>
</li>
<li>
<Link href="/another/first">another first page</Link>
</li>
<li>
<Link href="/another/second">another second page</Link>
</li>
<li>
<Link href="/image-import">image import page</Link>
</li>
</ul>
</main>
)
}
export async function GET() {
return Response.json({ answer: 42 })
}
export async function GET() {
return new Response('this is plain text')
}
import Link from 'next/link'
import img from './test.png'
export default function ImageImport() {
return (
<main>
<h1>Image Import</h1>
<ul>
<li>
<Link href="/">Visit the home page</Link>
</li>
<li>
<a href={img.src}>View the image</a>
</li>
</ul>
</main>
)
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<main>
<h1>Home</h1>
<ul>
<li>
<Link href="/another">another no trailingslash</Link>
</li>
<li>
<Link href="/another/">another has trailingslash</Link>
</li>
<li>
<Link href="/another/first">another first page</Link>
</li>
<li>
<Link href="/another/second">another second page</Link>
</li>
<li>
<Link href="/image-import">image import page</Link>
</li>
</ul>
</main>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true,
experimental: {
appDir: true,
},
generateBuildId() {
return 'test-build-id'
},
}
module.exports = nextConfig
/* eslint-env jest */
import { join } from 'path'
import { promisify } from 'util'
import fs from 'fs-extra'
import webdriver from 'next-webdriver'
import globOrig from 'glob'
import {
File,
nextBuild,
nextExport,
startStaticServer,
stopApp,
waitFor,
} from 'next-test-utils'
const glob = promisify(globOrig)
const appDir = join(__dirname, '..')
const distDir = join(__dirname, '.next')
const exportDir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js'))
const slugPage = new File(join(appDir, 'app/another/[slug]/page.js'))
const delay = 100
async function runTests({
trailingSlash,
dynamic,
}: {
trailingSlash?: boolean
dynamic?: string
}) {
if (trailingSlash) {
nextConfig.replace(
'trailingSlash: true,',
`trailingSlash: ${trailingSlash},`
)
}
if (dynamic) {
slugPage.replace(
`const dynamic = 'force-static'`,
`const dynamic = ${dynamic}`
)
}
await fs.remove(distDir)
await fs.remove(exportDir)
await nextBuild(appDir)
await nextExport(appDir, { outdir: exportDir })
const app = await startStaticServer(exportDir)
const address = app.address()
const appPort = typeof address !== 'string' ? address.port : 3000
try {
const a = (n: number) => `li:nth-child(${n}) a`
console.log('[navigate]')
const browser = await webdriver(appPort, '/')
expect(await browser.elementByCss('h1').text()).toBe('Home')
expect(await browser.elementByCss(a(1)).text()).toBe(
'another no trailingslash'
)
await browser.elementByCss(a(1)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Another')
expect(await browser.elementByCss(a(1)).text()).toBe('Visit the home page')
await browser.elementByCss(a(1)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Home')
expect(await browser.elementByCss(a(2)).text()).toBe(
'another has trailingslash'
)
await browser.elementByCss(a(2)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Another')
expect(await browser.elementByCss(a(1)).text()).toBe('Visit the home page')
await browser.elementByCss(a(1)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Home')
expect(await browser.elementByCss(a(3)).text()).toBe('another first page')
await browser.elementByCss(a(3)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('first')
expect(await browser.elementByCss(a(1)).text()).toBe('Visit another page')
await browser.elementByCss(a(1)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Another')
expect(await browser.elementByCss(a(4)).text()).toBe('another second page')
await browser.elementByCss(a(4)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('second')
expect(await browser.elementByCss(a(1)).text()).toBe('Visit another page')
await browser.elementByCss(a(1)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Another')
expect(await browser.elementByCss(a(5)).text()).toBe('image import page')
await browser.elementByCss(a(5)).click()
await waitFor(delay)
expect(await browser.elementByCss('h1').text()).toBe('Image Import')
expect(await browser.elementByCss(a(2)).text()).toBe('View the image')
expect(await browser.elementByCss(a(2)).getAttribute('href')).toContain(
'/test.3f1a293b.png'
)
} finally {
await stopApp(app)
nextConfig.restore()
slugPage.restore()
}
}
describe('app dir with next export', () => {
it.each([{ trailingSlash: false }, { trailingSlash: true }])(
"should work with trailingSlash '$trailingSlash'",
async ({ trailingSlash }) => {
await runTests({ trailingSlash })
}
)
it.each([
{ dynamic: 'undefined' },
{ dynamic: "'error'" },
{ dynamic: "'force-static'" },
])('should work with dynamic $dynamic', async ({ dynamic }) => {
await runTests({ dynamic })
const opts = { cwd: exportDir, nodir: true }
const files = ((await glob('**/*', opts)) as string[])
.filter((f) => !f.startsWith('_next/static/chunks/'))
.sort()
expect(files).toEqual([
'404.html',
'404/index.html',
// TODO-METADATA: favicon.ico should not be here
'_next/static/media/favicon.603d046c.ico',
'_next/static/media/test.3f1a293b.png',
'_next/static/test-build-id/_buildManifest.js',
'_next/static/test-build-id/_ssgManifest.js',
'another/first/index.html',
'another/first/index.txt',
'another/index.html',
'another/index.txt',
'another/second/index.html',
'another/second/index.txt',
'api/json',
'api/txt',
'favicon.ico',
'image-import/index.html',
'image-import/index.txt',
'index.html',
'index.txt',
'robots.txt',
])
})
it("should throw when dynamic 'force-dynamic'", async () => {
slugPage.replace(
`const dynamic = 'force-static'`,
`const dynamic = 'force-dynamic'`
)
await fs.remove(distDir)
await fs.remove(exportDir)
let result = { code: 0, stderr: '' }
try {
result = await nextBuild(appDir, [], { stderr: true })
} finally {
nextConfig.restore()
slugPage.restore()
}
expect(result.code).toBe(1)
expect(result.stderr).toContain(
'export const dynamic = "force-dynamic" on page "/another/[slug]" cannot be used with "output: export".'
)
})
})
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