Unverified Commit ca13752e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Implement `experimentalPrerender` option (#7983)

* Revert "Remove Old Prerender Implementation (#8218)"

This reverts commit 2ab300dd.

* Add contentHandler for page config

* Rename config from contentHandler to re-use
experimentalPrerender

* Remove un-needed changes

* Replace backslashes for manifest

* Update manifest output format

* Make prerender: true enable SPR behavior and update
to merge prerender-manifest for flying-shuttle

* Fix output path for / prerender file

* Add dynamic routes to test suite

* Add generating and previewing of skeletons
for prerendered dynamic routes

* remove inline prerender option

* update to not replace getInitialProps which allows
nested getInitialProps and add query when fetching prerender

* Apply suggestions from code review
Co-Authored-By: 's avatarJoe Haddad <timer150@gmail.com>

* Remove legacy prerender option

* Apply suggestions from review

* Apply more suggestions from review

* Apply suggestions from code review
Co-Authored-By: 's avatarJoe Haddad <timer150@gmail.com>

* Add handling of error when parsing json

* Update handling of moving exported pages

* Rename nextPreviewSkeleton to _nextPreviewSkeleton

* bump
parent a3d64abe
...@@ -4,6 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server' ...@@ -4,6 +4,7 @@ export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server' export const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'
export const PAGES_MANIFEST = 'pages-manifest.json' export const PAGES_MANIFEST = 'pages-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json' export const BUILD_MANIFEST = 'build-manifest.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json'
export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json' export const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'
export const CHUNK_GRAPH_MANIFEST = 'compilation-modules.json' export const CHUNK_GRAPH_MANIFEST = 'compilation-modules.json'
export const SERVER_DIRECTORY = 'server' export const SERVER_DIRECTORY = 'server'
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
// tslint:disable:no-console // tslint:disable:no-console
import { ParsedUrlQuery } from 'querystring' import { ParsedUrlQuery } from 'querystring'
import { ComponentType } from 'react' import { ComponentType } from 'react'
import { parse, UrlObject } from 'url' import { parse, UrlObject, format } from 'url'
import mitt, { MittEmitter } from '../mitt' import mitt, { MittEmitter } from '../mitt'
import { import {
...@@ -579,13 +579,29 @@ export default class Router implements BaseRouter { ...@@ -579,13 +579,29 @@ export default class Router implements BaseRouter {
} }
this.clc = cancel this.clc = cancel
const { Component: App } = this.components['/_app'] const { Component: App } = this.components['/_app']
let props
const props = await loadGetInitialProps<AppContextType<Router>>(App, { if ((Component as any).__NEXT_PRERENDER) {
AppTree: this._wrapApp(App), const url = format({
Component, pathname: ctx.asPath,
router: this, query: ctx.query,
ctx, })
}) const res = await fetch(url, {
headers: { 'content-type': 'application/json' },
})
props = {
pageProps: res.ok
? await res.json().catch(err => ({ error: err.message }))
: { error: 'failed to load prerender', statusCode: res.status },
}
} else {
props = await loadGetInitialProps<AppContextType<Router>>(App, {
AppTree: this._wrapApp(App),
Component,
router: this,
ctx,
})
}
if (cancel === this.clc) { if (cancel === this.clc) {
this.clc = null this.clc = null
......
...@@ -62,6 +62,7 @@ export type NEXT_DATA = { ...@@ -62,6 +62,7 @@ export type NEXT_DATA = {
assetPrefix?: string assetPrefix?: string
runtimeConfig?: { [key: string]: any } runtimeConfig?: { [key: string]: any }
nextExport?: boolean nextExport?: boolean
skeleton?: boolean
dynamicIds?: string[] dynamicIds?: string[]
err?: Error & { statusCode?: number } err?: Error & { statusCode?: number }
} }
......
...@@ -133,6 +133,7 @@ type RenderOpts = { ...@@ -133,6 +133,7 @@ type RenderOpts = {
assetPrefix?: string assetPrefix?: string
err?: Error | null err?: Error | null
nextExport?: boolean nextExport?: boolean
skeleton?: boolean
dev?: boolean dev?: boolean
ampMode?: any ampMode?: any
ampPath?: string ampPath?: string
...@@ -164,6 +165,7 @@ function renderDocument( ...@@ -164,6 +165,7 @@ function renderDocument(
assetPrefix, assetPrefix,
runtimeConfig, runtimeConfig,
nextExport, nextExport,
skeleton,
dynamicImportsIds, dynamicImportsIds,
dangerousAsPath, dangerousAsPath,
err, err,
...@@ -208,6 +210,7 @@ function renderDocument( ...@@ -208,6 +210,7 @@ function renderDocument(
assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
nextExport, // If this is a page exported by `next export` nextExport, // If this is a page exported by `next export`
skeleton, // If this is a skeleton page for experimentalPrerender
dynamicIds: dynamicIds:
dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds, dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
...@@ -255,7 +258,8 @@ export async function renderToHTML( ...@@ -255,7 +258,8 @@ export async function renderToHTML(
} = renderOpts } = renderOpts
await Loadable.preloadAll() // Make sure all dynamic imports are loaded await Loadable.preloadAll() // Make sure all dynamic imports are loaded
let isStaticPage = false let isStaticPage = pageConfig.experimentalPrerender === true
let isSkeleton = false
if (dev) { if (dev) {
const { isValidElementType } = require('react-is') const { isValidElementType } = require('react-is')
...@@ -290,6 +294,11 @@ export async function renderToHTML( ...@@ -290,6 +294,11 @@ export async function renderToHTML(
renderOpts.nextExport = true renderOpts.nextExport = true
} }
} }
// might want to change previewing of skeleton from `?_nextPreviewSkeleton=(truthy)`
isSkeleton =
pageConfig.experimentalPrerender === true && !!query._nextPreviewSkeleton
// remove from query so it doesn't end up in document
delete query._nextPreviewSkeleton
// @ts-ignore url will always be set // @ts-ignore url will always be set
const asPath: string = req.url const asPath: string = req.url
...@@ -336,25 +345,36 @@ export async function renderToHTML( ...@@ -336,25 +345,36 @@ export async function renderToHTML(
) )
try { try {
props = await loadGetInitialProps(App, { props = isSkeleton
Component, ? { pageProps: {} }
AppTree: (props: any) => { : await loadGetInitialProps(App, {
const appProps = { ...props, Component, router } Component,
return ( AppTree: (props: any) => {
<AppContainer> const appProps = { ...props, Component, router }
<App {...appProps} /> return (
</AppContainer> <AppContainer>
) <App {...appProps} />
}, </AppContainer>
router, )
ctx, },
}) router,
ctx,
})
} catch (err) { } catch (err) {
if (!dev || !err) throw err if (!dev || !err) throw err
ctx.err = err ctx.err = err
renderOpts.err = err renderOpts.err = err
} }
if (
pageConfig.experimentalPrerender === true &&
req.headers['content-type'] === 'application/json'
) {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify(props.pageProps || {}))
return null
}
// the response might be finished on the getInitialProps call // the response might be finished on the getInitialProps call
if (isResSent(res)) return null if (isResSent(res)) return null
...@@ -499,6 +519,7 @@ export async function renderToHTML( ...@@ -499,6 +519,7 @@ export async function renderToHTML(
// update renderOpts so export knows current state // update renderOpts so export knows current state
renderOpts.inAmpMode = inAmpMode renderOpts.inAmpMode = inAmpMode
renderOpts.hybridAmp = hybridAmp renderOpts.hybridAmp = hybridAmp
if (isSkeleton) renderOpts.skeleton = true
let html = renderDocument(Document, { let html = renderDocument(Document, {
...renderOpts, ...renderOpts,
......
...@@ -10,4 +10,5 @@ export type PageConfig = { ...@@ -10,4 +10,5 @@ export type PageConfig = {
*/ */
bodyParser?: { sizeLimit?: number | string } | false bodyParser?: { sizeLimit?: number | string } | false
} }
experimentalPrerender?: boolean
} }
...@@ -3,10 +3,13 @@ import { NodePath } from '@babel/traverse' ...@@ -3,10 +3,13 @@ import { NodePath } from '@babel/traverse'
import * as BabelTypes from '@babel/types' import * as BabelTypes from '@babel/types'
import { PageConfig } from 'next-server/types' import { PageConfig } from 'next-server/types'
const configKeys = new Set(['amp'])
export const dropBundleIdentifier = '__NEXT_DROP_CLIENT_FILE__' export const dropBundleIdentifier = '__NEXT_DROP_CLIENT_FILE__'
// replace progam path with just a variable with the drop identifier const configKeys = new Set(['amp', 'experimentalPrerender'])
const pageComponentVar = '__NEXT_COMP'
const prerenderId = '__NEXT_PRERENDER'
// replace program path with just a variable with the drop identifier
function replaceBundle(path: any, t: typeof BabelTypes) { function replaceBundle(path: any, t: typeof BabelTypes) {
path.parentPath.replaceWith( path.parentPath.replaceWith(
t.program( t.program(
...@@ -28,6 +31,7 @@ function replaceBundle(path: any, t: typeof BabelTypes) { ...@@ -28,6 +31,7 @@ function replaceBundle(path: any, t: typeof BabelTypes) {
} }
interface ConfigState { interface ConfigState {
isPrerender?: boolean
bundleDropped?: boolean bundleDropped?: boolean
} }
...@@ -84,12 +88,42 @@ export default function nextPageConfig({ ...@@ -84,12 +88,42 @@ export default function nextPageConfig({
state.bundleDropped = true state.bundleDropped = true
return return
} }
state.isPrerender = config.experimentalPrerender === true
}, },
}, },
state state
) )
}, },
}, },
ExportDefaultDeclaration(path, state: ConfigState) {
if (!state.isPrerender) {
return
}
const prev = t.cloneDeep(path.node.declaration)
// workaround to allow assigning a ClassDeclaration to a variable
// babel throws error without
if (prev.type.endsWith('Declaration')) {
prev.type = prev.type.replace(/Declaration$/, 'Expression') as any
}
path.insertBefore([
t.variableDeclaration('const', [
t.variableDeclarator(t.identifier(pageComponentVar), prev as any),
]),
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier(pageComponentVar),
t.identifier(prerenderId)
),
t.booleanLiteral(true)
),
])
path.node.declaration = t.identifier(pageComponentVar)
},
}, },
} }
} }
...@@ -2,7 +2,7 @@ import { Sema } from 'async-sema' ...@@ -2,7 +2,7 @@ import { Sema } from 'async-sema'
import crypto from 'crypto' import crypto from 'crypto'
import fs from 'fs' import fs from 'fs'
import mkdirpModule from 'mkdirp' import mkdirpModule from 'mkdirp'
import { CHUNK_GRAPH_MANIFEST } from 'next-server/constants' import { CHUNK_GRAPH_MANIFEST, PRERENDER_MANIFEST } from 'next-server/constants'
import { EOL } from 'os' import { EOL } from 'os'
import path from 'path' import path from 'path'
import { promisify } from 'util' import { promisify } from 'util'
...@@ -11,11 +11,16 @@ import { recursiveDelete } from '../lib/recursive-delete' ...@@ -11,11 +11,16 @@ import { recursiveDelete } from '../lib/recursive-delete'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import * as Log from './output/log' import * as Log from './output/log'
import { PageInfo } from './utils' import { PageInfo } from './utils'
import { PrerenderRoute } from '.'
const FILE_BUILD_ID = 'HEAD_BUILD_ID' const FILE_BUILD_ID = 'HEAD_BUILD_ID'
const FILE_UPDATED_AT = 'UPDATED_AT' const FILE_UPDATED_AT = 'UPDATED_AT'
const DIR_FILES_NAME = 'files' const DIR_FILES_NAME = 'files'
const MAX_SHUTTLES = 3 const MAX_SHUTTLES = 3
const SAVED_MANIFESTS = [
'serverless/pages-manifest.json',
'prerender-manifest.json',
]
const mkdirp = promisify(mkdirpModule) const mkdirp = promisify(mkdirpModule)
const fsReadFile = promisify(fs.readFile) const fsReadFile = promisify(fs.readFile)
...@@ -304,28 +309,50 @@ export class FlyingShuttle { ...@@ -304,28 +309,50 @@ export class FlyingShuttle {
return unchangedPages return unchangedPages
} }
mergePagesManifest = async (): Promise<void> => { mergeManifests = async (): Promise<void> => {
const savedPagesManifest = path.join( for (const manifestPath of SAVED_MANIFESTS) {
this.shuttleDirectory, const savedPagesManifest = path.join(
DIR_FILES_NAME, this.shuttleDirectory,
'serverless/pages-manifest.json' DIR_FILES_NAME,
) manifestPath
if (!(await fileExists(savedPagesManifest))) return )
if (!(await fileExists(savedPagesManifest))) return
const saved = JSON.parse(await fsReadFile(savedPagesManifest, 'utf8')) const saved = JSON.parse(await fsReadFile(savedPagesManifest, 'utf8'))
const currentPagesManifest = path.join( const currentPagesManifest = path.join(this.distDirectory, manifestPath)
this.distDirectory, const current = JSON.parse(await fsReadFile(currentPagesManifest, 'utf8'))
'serverless/pages-manifest.json'
)
const current = JSON.parse(await fsReadFile(currentPagesManifest, 'utf8'))
await fsWriteFile( if (manifestPath === PRERENDER_MANIFEST) {
currentPagesManifest, const prerenderRoutes = new Map<string, PrerenderRoute>()
JSON.stringify({
...saved, if (Array.isArray(saved.prerenderRoutes)) {
...current, saved.prerenderRoutes.forEach((route: PrerenderRoute) => {
}) prerenderRoutes.set(route.path, route)
) })
}
if (Array.isArray(current.prerenderRoutes)) {
current.prerenderRoutes.forEach((route: PrerenderRoute) => {
prerenderRoutes.set(route.path, route)
})
}
await fsWriteFile(
currentPagesManifest,
JSON.stringify({
prerenderRoutes: [...prerenderRoutes.values()],
})
)
} else {
await fsWriteFile(
currentPagesManifest,
JSON.stringify({
...saved,
...current,
})
)
}
}
} }
restorePage = async ( restorePage = async (
...@@ -518,14 +545,12 @@ export class FlyingShuttle { ...@@ -518,14 +545,12 @@ export class FlyingShuttle {
}) })
) )
await fsCopyFile( for (const manifestPath of SAVED_MANIFESTS) {
path.join(this.distDirectory, 'serverless/pages-manifest.json'), await fsCopyFile(
path.join( path.join(this.distDirectory, manifestPath),
this.shuttleDirectory, path.join(this.shuttleDirectory, DIR_FILES_NAME, manifestPath)
DIR_FILES_NAME,
'serverless/pages-manifest.json'
) )
) }
Log.info(`flying shuttle payload: ${usedChunks.size + 2} files`) Log.info(`flying shuttle payload: ${usedChunks.size + 2} files`)
Log.ready('flying shuttle docked') Log.ready('flying shuttle docked')
......
...@@ -6,6 +6,7 @@ import { ...@@ -6,6 +6,7 @@ import {
CHUNK_GRAPH_MANIFEST, CHUNK_GRAPH_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
PRERENDER_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
} from 'next-server/constants' } from 'next-server/constants'
...@@ -50,8 +51,14 @@ const fsReadFile = promisify(fs.readFile) ...@@ -50,8 +51,14 @@ const fsReadFile = promisify(fs.readFile)
const fsWriteFile = promisify(fs.writeFile) const fsWriteFile = promisify(fs.writeFile)
const mkdirp = promisify(mkdirpOrig) const mkdirp = promisify(mkdirpOrig)
const sprPages = new Set<string>()
const staticCheckWorker = require.resolve('./static-checker') const staticCheckWorker = require.resolve('./static-checker')
export type PrerenderRoute = {
path: string
contentTypes: string[]
}
export default async function build(dir: string, conf = null): Promise<void> { export default async function build(dir: string, conf = null): Promise<void> {
if (!(await isWriteable(dir))) { if (!(await isWriteable(dir))) {
throw new Error( throw new Error(
...@@ -370,6 +377,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -370,6 +377,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (result.static && customAppGetInitialProps === false) { if (result.static && customAppGetInitialProps === false) {
staticPages.add(page) staticPages.add(page)
isStatic = true isStatic = true
} else if (result.prerender) {
sprPages.add(page)
} }
} catch (err) { } catch (err) {
if (err.message !== 'INVALID_DEFAULT_EXPORT') throw err if (err.message !== 'INVALID_DEFAULT_EXPORT') throw err
...@@ -411,12 +420,14 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -411,12 +420,14 @@ export default async function build(dir: string, conf = null): Promise<void> {
await writeBuildId(distDir, buildId, selectivePageBuilding) await writeBuildId(distDir, buildId, selectivePageBuilding)
if (staticPages.size > 0) { if (staticPages.size > 0 || sprPages.size > 0) {
const combinedPages = [...staticPages, ...sprPages]
const exportApp = require('../export').default const exportApp = require('../export').default
const exportOptions = { const exportOptions = {
sprPages,
silent: true, silent: true,
buildExport: true, buildExport: true,
pages: Array.from(staticPages), pages: combinedPages,
outdir: path.join(distDir, 'export'), outdir: path.join(distDir, 'export'),
} }
const exportConfig = { const exportConfig = {
...@@ -425,49 +436,78 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -425,49 +436,78 @@ export default async function build(dir: string, conf = null): Promise<void> {
exportTrailingSlash: false, exportTrailingSlash: false,
} }
await exportApp(dir, exportOptions, exportConfig) await exportApp(dir, exportOptions, exportConfig)
const toMove = await recursiveReadDir(exportOptions.outdir, /.*\.html$/)
let serverDir: string = ''
// remove server bundles that were exported // remove server bundles that were exported
for (const page of staticPages) { for (const page of staticPages) {
const { serverBundle } = pageInfos.get(page)! const { serverBundle } = pageInfos.get(page)!
if (!serverDir) {
serverDir = path.join(
serverBundle.split(/(\/|\\)pages/).shift()!,
'pages'
)
}
await fsUnlink(serverBundle) await fsUnlink(serverBundle)
} }
for (const file of toMove) { const exportedFiles = new Set(
await recursiveReadDir(exportOptions.outdir, /.*\.html$/)
)
const moveExportedPage = async (page: string, file: string) => {
const isSpr = sprPages.has(page)
file = `${file}.html`
const orig = path.join(exportOptions.outdir, file) const orig = path.join(exportOptions.outdir, file)
const dest = path.join(serverDir, file)
const relativeDest = (isLikeServerless const relativeDest = (isLikeServerless
? path.join('pages', file) ? path.join('pages', file)
: path.join('static', buildId, 'pages', file) : path.join('static', buildId, 'pages', file)
).replace(/\\/g, '/') ).replace(/\\/g, '/')
let page = file.split('.html')[0].replace(/\\/g, '/') const dest = path.join(
pagesManifest[page] = relativeDest distDir,
page = page === '/index' ? '/' : page isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
pagesManifest[page] = relativeDest relativeDest
staticPages.add(page) )
if (!isSpr) {
pagesManifest[page] = relativeDest
if (page === '/') pagesManifest['/index'] = relativeDest
if (page === '/.amp') pagesManifest['/index.amp'] = relativeDest
}
await mkdirp(path.dirname(dest)) await mkdirp(path.dirname(dest))
await fsMove(orig, dest) await fsMove(orig, dest)
} }
for (const page of combinedPages) {
let file = page === '/' ? '/index' : page
await moveExportedPage(page, file)
const hasAmp = exportedFiles.has(`${file}.amp.html`)
if (hasAmp) await moveExportedPage(`${page}.amp`, `${file}.amp`)
}
// remove temporary export folder // remove temporary export folder
await recursiveDelete(exportOptions.outdir) await recursiveDelete(exportOptions.outdir)
await fsRmdir(exportOptions.outdir) await fsRmdir(exportOptions.outdir)
await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8') await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8')
} }
if (sprPages.size > 0) {
const prerenderRoutes: PrerenderRoute[] = []
sprPages.forEach(pg => {
prerenderRoutes.push({
path: pg,
contentTypes: ['application/json', 'text/html'],
})
})
await fsWriteFile(
path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify({ prerenderRoutes }),
'utf8'
)
}
staticPages.forEach(pg => allStaticPages.add(pg)) staticPages.forEach(pg => allStaticPages.add(pg))
pageInfos.forEach((info: PageInfo, key: string) => { pageInfos.forEach((info: PageInfo, key: string) => {
allPageInfos.set(key, info) allPageInfos.set(key, info)
}) })
if (flyingShuttle) { if (flyingShuttle) {
await flyingShuttle.mergePagesManifest() await flyingShuttle.mergeManifests()
await flyingShuttle.save(allStaticPages, pageInfos) await flyingShuttle.save(allStaticPages, pageInfos)
} }
......
...@@ -265,7 +265,7 @@ export async function getPageSizeInKb( ...@@ -265,7 +265,7 @@ export async function getPageSizeInKb(
export function isPageStatic( export function isPageStatic(
serverBundle: string, serverBundle: string,
runtimeEnvConfig: any runtimeEnvConfig: any
): { static?: boolean } { ): { static?: boolean; prerender?: boolean } {
try { try {
require('next-server/config').setConfig(runtimeEnvConfig) require('next-server/config').setConfig(runtimeEnvConfig)
const mod = require(serverBundle) const mod = require(serverBundle)
...@@ -277,6 +277,7 @@ export function isPageStatic( ...@@ -277,6 +277,7 @@ export function isPageStatic(
return { return {
static: typeof (Comp as any).getInitialProps !== 'function', static: typeof (Comp as any).getInitialProps !== 'function',
prerender: mod.config && mod.config.experimentalPrerender === true,
} }
} catch (err) { } catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return {} if (err.code === 'MODULE_NOT_FOUND') return {}
......
...@@ -173,8 +173,19 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => { ...@@ -173,8 +173,19 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
render({ App, Component, props, err, emitter }) render({ App, Component, props, err, emitter })
} }
}) })
const renderCtx = { App, Component, props, err: initialErr, emitter }
render(renderCtx)
render({ App, Component, props, err: initialErr, emitter }) if (window.__NEXT_DATA__.skeleton && Component.getInitialProps) {
const appCtx = {
router,
AppTree: wrapApp(App),
Component: Component,
ctx: { pathname: page, asPath, query }
}
props.pageProps = (await App.getInitialProps(appCtx)).pageProps
render(renderCtx)
}
return emitter return emitter
} }
......
...@@ -159,6 +159,10 @@ export default async function (dir, options, configuration) { ...@@ -159,6 +159,10 @@ export default async function (dir, options, configuration) {
} }
result[worker].pathMap[route] = exportPathMap[route] result[worker].pathMap[route] = exportPathMap[route]
result[worker].paths.push(route) result[worker].paths.push(route)
if (options.sprPages && options.sprPages.has(route)) {
result[worker].pathMap[route].sprPage = true
}
return result return result
}, []) }, [])
......
...@@ -37,9 +37,10 @@ process.on( ...@@ -37,9 +37,10 @@ process.on(
try { try {
const work = async path => { const work = async path => {
await sema.acquire() await sema.acquire()
const ampPath = `${path === '/' ? '/index' : path}.amp`
const { page } = exportPathMap[path]
let { query = {} } = exportPathMap[path] let { query = {} } = exportPathMap[path]
const { page, sprPage } = exportPathMap[path]
const filePath = path === '/' ? '/index' : path
const ampPath = `${filePath}.amp`
// Check if the page is a specified dynamic route // Check if the page is a specified dynamic route
if (isDynamicRoute(page) && page !== path) { if (isDynamicRoute(page) && page !== path) {
...@@ -73,14 +74,20 @@ process.on( ...@@ -73,14 +74,20 @@ process.on(
...headerMocks ...headerMocks
} }
if (sprPage && isDynamicRoute(page)) {
query._nextPreviewSkeleton = 1
// pass via `req` to avoid adding code to serverless bundle
req.url +=
(req.url.includes('?') ? '&' : '?') + '_nextPreviewSkeleton=1'
}
envConfig.setConfig({ envConfig.setConfig({
serverRuntimeConfig, serverRuntimeConfig,
publicRuntimeConfig: renderOpts.runtimeConfig publicRuntimeConfig: renderOpts.runtimeConfig
}) })
let htmlFilename = `${path}${sep}index.html` let htmlFilename = `${filePath}${sep}index.html`
if (!subFolders) htmlFilename = `${filePath}.html`
if (!subFolders) htmlFilename = `${path}.html`
const pageExt = extname(page) const pageExt = extname(page)
const pathExt = extname(path) const pathExt = extname(path)
...@@ -92,6 +99,7 @@ process.on( ...@@ -92,6 +99,7 @@ process.on(
// If the path is the root, just use index.html // If the path is the root, just use index.html
htmlFilename = 'index.html' htmlFilename = 'index.html'
} }
const baseDir = join(outDir, dirname(htmlFilename)) const baseDir = join(outDir, dirname(htmlFilename))
const htmlFilepath = join(outDir, htmlFilename) const htmlFilepath = join(outDir, htmlFilename)
......
module.exports = {
target: 'serverless'
}
import Link from 'next/link'
export const config = { experimentalPrerender: true }
const wrapPage = Comp => {
Comp.getInitialProps = () => ({ world: 'world' })
return Comp
}
export default wrapPage(({ world }) => (
<>
<p>hello {world}</p>
<Link href='/'>
<a id='home'>to home</a>
</Link>
<br />
<Link href='/something'>
<a id='somethin'>to something</a>
</Link>
</>
))
import Link from 'next/link'
export const config = { experimentalPrerender: true }
const Comment = ({ data }) => (
<>
<p>Comment: {data}</p>
<Link href='/'>
<a id='home'>to home</a>
</Link>
</>
)
Comment.getInitialProps = () => ({
data: typeof window === 'undefined' ? 'SSR' : 'Skeleton'
})
export default Comment
import React from 'react'
import Link from 'next/link'
export const config = { experimentalPrerender: true }
export default class Post extends React.Component {
static async getInitialProps () {
return {
data: typeof window === 'undefined' ? 'SSR' : 'Skeleton'
}
}
render () {
return (
<>
<p>Post: {this.props.data}</p>
<Link href='/'>
<a id='home'>to home</a>
</Link>
</>
)
}
}
import Link from 'next/link'
export const config = { experimentalPrerender: true }
const Page = ({ world }) => {
return (
<>
<p>hello {world}</p>
<Link href='/another'>
<a id='another'>to another</a>
</Link>
<br />
<Link href='/something'>
<a id='something'>to something</a>
</Link>
<br />
<Link href='/normal'>
<a id='normal'>to normal</a>
</Link>
<br />
<Link href='/blog/[post]' as='/blog/post-1'>
<a id='post-1'>to dynamic</a>
</Link>
<br />
<Link href='/blog/[post]/[comment]' as='/blog/post-1/comment-1'>
<a id='comment-1'>to another dynamic</a>
</Link>
</>
)
}
Page.getInitialProps = () => ({ world: 'world' })
export default Page
export default () => <p id='normal-text'>a normal page</p>
import React, { Component } from 'react'
import Link from 'next/link'
export const config = { experimentalPrerender: true }
class Page extends Component {
static async getInitialProps () {
return { world: 'world' }
}
render () {
return (
<>
<p>hello {this.props.world}</p>
<Link href='/'>
<a id='home'>to home</a>
</Link>
<br />
<Link href='/another'>
<a id='another'>to another</a>
</Link>
</>
)
}
}
export default Page
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
renderViaHTTP,
fetchViaHTTP,
findPort,
launchApp,
killApp,
nextBuild,
nextStart,
waitFor
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
const appDir = join(__dirname, '..')
let app
let appPort
const runTests = () => {
it('should navigate between pages successfully', async () => {
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /another
await browser.elementByCss('#another').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#another')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /something
await browser.elementByCss('#something').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#post-1')
// go to /blog/post-1
await browser.elementByCss('#post-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Post:.*?SSR/)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /blog/post-1/comment-1
await browser.elementByCss('#comment-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Comment:.*?SSR/)
await browser.close()
})
it('should SSR content correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/hello.*?world/)
})
it('should navigate to a normal page and back', async () => {
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
await browser.elementByCss('#normal').click()
await browser.waitForElementByCss('#normal-text')
text = await browser.elementByCss('#normal-text').text()
expect(text).toMatch(/a normal page/)
})
it('should return JSON when content-type is set', async () => {
const data = await fetchViaHTTP(appPort, '/', undefined, {
headers: {
'content-type': 'application/json'
}
}).then(res => res.ok && res.json())
expect(data.world).toMatch('world')
})
it('should generate skeleton without calling getInitialProps', async () => {
let html = await renderViaHTTP(
appPort,
'/blog/post-1?_nextPreviewSkeleton=1'
)
expect(html).not.toMatch(/Post:.*?SSR/)
html = await renderViaHTTP(
appPort,
'/blog/post-1/comment-1?_nextPreviewSkeleton=1'
)
expect(html).not.toMatch(/Comment:.*?SSR/)
})
it('should call getInitialProps client-side when viewing skeleton', async () => {
let browser = await webdriver(
appPort,
'/blog/post-1?_nextPreviewSkeleton=1'
)
await waitFor(1000)
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/Post:.*?Skeleton/)
await browser.close()
browser = await webdriver(
appPort,
'/blog/post-1/comment-1?_nextPreviewSkeleton=1'
)
await waitFor(1000)
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Comment:.*?Skeleton/)
await browser.close()
})
}
describe('SPR Prerender', () => {
describe('development mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
it('outputs a prerender-manifest correctly', async () => {
const manifest = require(join(appDir, '.next', 'prerender-manifest.json'))
const pages = manifest.prerenderRoutes.map(route => route.path)
expect(JSON.stringify(pages.sort())).toBe(
JSON.stringify(
[
'/',
'/another',
'/something',
'/blog/[post]',
'/blog/[post]/[comment]'
].sort()
)
)
})
})
})
...@@ -99,6 +99,6 @@ describe('Production response size', () => { ...@@ -99,6 +99,6 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
expect(responseSizeKilobytes).toBeLessThanOrEqual(186) // Kilobytes expect(responseSizeKilobytes).toBeLessThanOrEqual(187) // Kilobytes
}) })
}) })
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