Commit fc7e235f authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Followup optimizations for new experimentalPrerender (#8287)

* Add checking for hybrid AMP during static check

* Update to always hit server for prerender data

* Add removing of SPR code when not used

* Add checking for hybrid AMP during static check

* Update to always hit server for prerender data

* Add removing of SPR code when not used

* Update dead code elimination
parent 35e7b21d
......@@ -605,19 +605,35 @@ export default class Router implements BaseRouter {
const { Component: App } = this.components['/_app']
let props
if ((Component as any).__NEXT_PRERENDER) {
const url = format({
pathname: ctx.asPath,
query: ctx.query,
})
const res = await fetch(url, {
if (
// @ts-ignore workaround for dead-code elimination
(self.__HAS_SPR || process.env.NODE_ENV !== 'production') &&
(Component as any).__NEXT_SPR
) {
let status: any
const url = ctx.asPath
? ctx.asPath
: format({
pathname: ctx.pathname,
query: ctx.query,
})
props = 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 },
}
.then(res => {
if (!res.ok) {
status = res.status
throw new Error('failed to load prerender data')
}
return res.json()
})
.then((pageProps: any) => {
return { pageProps }
})
.catch((err: Error) => {
return { error: err.message, status }
})
} else {
props = await loadGetInitialProps<AppContextType<Router>>(App, {
AppTree: this._wrapApp(App),
......
......@@ -299,6 +299,7 @@ export async function renderToHTML(
pageConfig.experimentalPrerender === true && !!query._nextPreviewSkeleton
// remove from query so it doesn't end up in document
delete query._nextPreviewSkeleton
if (isSkeleton) renderOpts.nextExport = true
// @ts-ignore url will always be set
const asPath: string = req.url
......@@ -310,6 +311,9 @@ export async function renderToHTML(
query,
asPath,
}
const isDataPrerender =
pageConfig.experimentalPrerender === true &&
req.headers['content-type'] === 'application/json'
const router = new ServerRouter(pathname, query, asPath)
let props: any
......@@ -345,31 +349,29 @@ export async function renderToHTML(
)
try {
props = isSkeleton
? { pageProps: {} }
: await loadGetInitialProps(App, {
Component,
AppTree: (props: any) => {
const appProps = { ...props, Component, router }
return (
<AppContainer>
<App {...appProps} />
</AppContainer>
)
},
router,
ctx,
})
props =
isSkeleton && !isDataPrerender
? { pageProps: {} }
: await loadGetInitialProps(App, {
Component,
AppTree: (props: any) => {
const appProps = { ...props, Component, router }
return (
<AppContainer>
<App {...appProps} />
</AppContainer>
)
},
router,
ctx,
})
} catch (err) {
if (!dev || !err) throw err
ctx.err = err
renderOpts.err = err
}
if (
pageConfig.experimentalPrerender === true &&
req.headers['content-type'] === 'application/json'
) {
if (isDataPrerender) {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify(props.pageProps || {}))
return null
......
......@@ -4,10 +4,12 @@ import * as BabelTypes from '@babel/types'
import { PageConfig } from 'next-server/types'
export const dropBundleIdentifier = '__NEXT_DROP_CLIENT_FILE__'
export const sprStatus = { used: false }
const configKeys = new Set(['amp', 'experimentalPrerender'])
const pageComponentVar = '__NEXT_COMP'
const prerenderId = '__NEXT_PRERENDER'
// this value can't be optimized by terser so the shorter the better
const prerenderId = '__NEXT_SPR'
// replace program path with just a variable with the drop identifier
function replaceBundle(path: any, t: typeof BabelTypes) {
......@@ -90,6 +92,7 @@ export default function nextPageConfig({
}
state.isPrerender = config.experimentalPrerender === true
sprStatus.used = sprStatus.used || state.isPrerender
},
},
state
......
......@@ -20,7 +20,6 @@ import workerFarm from 'worker-farm'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import { recursiveDelete } from '../lib/recursive-delete'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
import { CompilerResult, runCompiler } from './compiler'
import { createEntrypoints, createPagesMapping } from './entries'
......@@ -51,7 +50,6 @@ const fsReadFile = promisify(fs.readFile)
const fsWriteFile = promisify(fs.writeFile)
const mkdirp = promisify(mkdirpOrig)
const sprPages = new Set<string>()
const staticCheckWorker = require.resolve('./static-checker')
export type PrerenderRoute = {
......@@ -290,8 +288,10 @@ export default async function build(dir: string, conf = null): Promise<void> {
PAGES_MANIFEST
)
const sprPages = new Set<string>()
const staticPages = new Set<string>()
const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>()
const pageInfos = new Map<string, PageInfo>()
const pagesManifest = JSON.parse(await fsReadFile(manifestPath, 'utf8'))
let customAppGetInitialProps: boolean | undefined
......@@ -374,6 +374,10 @@ export default async function build(dir: string, conf = null): Promise<void> {
})
staticCheckSema.release()
if (result.isHybridAmp) {
hybridAmpPages.add(page)
}
if (result.static && customAppGetInitialProps === false) {
staticPages.add(page)
isStatic = true
......@@ -443,12 +447,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
await fsUnlink(serverBundle)
}
const exportedFiles = new Set(
(await recursiveReadDir(exportOptions.outdir, /.*\.html$/)).map(p =>
p.replace(/\\/g, '/')
)
)
const moveExportedPage = async (page: string, file: string) => {
const isSpr = sprPages.has(page)
file = `${file}.html`
......@@ -476,7 +474,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
for (const page of combinedPages) {
let file = page === '/' ? '/index' : page
await moveExportedPage(page, file)
const hasAmp = exportedFiles.has(`${file}.amp.html`)
const hasAmp = hybridAmpPages.has(page)
if (hasAmp) await moveExportedPage(`${page}.amp`, `${file}.amp`)
}
......
......@@ -265,7 +265,7 @@ export async function getPageSizeInKb(
export function isPageStatic(
serverBundle: string,
runtimeEnvConfig: any
): { static?: boolean; prerender?: boolean } {
): { static?: boolean; prerender?: boolean; isHybridAmp?: boolean } {
try {
require('next-server/config').setConfig(runtimeEnvConfig)
const mod = require(serverBundle)
......@@ -274,10 +274,12 @@ export function isPageStatic(
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') {
throw new Error('INVALID_DEFAULT_EXPORT')
}
const config = mod.config || {}
return {
static: typeof (Comp as any).getInitialProps !== 'function',
prerender: mod.config && mod.config.experimentalPrerender === true,
prerender: config.experimentalPrerender === true,
isHybridAmp: config.amp === 'hybrid',
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return {}
......
......@@ -6,6 +6,7 @@ import { SourceMapConsumer } from 'source-map'
import { SourceMapSource, RawSource } from 'webpack-sources'
import { RequestShortener } from 'webpack'
import TaskRunner from './TaskRunner'
import { sprStatus } from '../../../../babel/plugins/next-page-config'
const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/
......@@ -173,6 +174,15 @@ export class TerserPlugin {
inputSourceMap = null
}
// force dead-code elimination for SPR related code if not used
const { compress } = this.options.terserOptions
if (compress) {
if (!compress.global_defs) {
compress.global_defs = {}
}
compress.global_defs['self.__HAS_SPR'] = !!sprStatus.used
}
const task = {
file,
input,
......
......@@ -88,7 +88,7 @@ class Container extends React.Component {
// If it's a dynamic route or has a querystring
if (
data.nextExport &&
(isDynamicRoute(router.pathname) || location.search)
(isDynamicRoute(router.pathname) || location.search || data.skeleton)
) {
// update query on mount for exported pages
router.replace(
......@@ -182,17 +182,6 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
const renderCtx = { App, Component, props, err: initialErr, emitter }
render(renderCtx)
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
}
......
......@@ -38,7 +38,7 @@ const renames = [
},
{
srcGlob: '.next/static/chunks/commons!(*.module.js)',
dest: 'next/static/chunks/commons-HASH.js'
dest: '.next/static/chunks/commons.HASH.js'
},
// modern
{
......@@ -51,7 +51,7 @@ const renames = [
},
{
srcGlob: '.next/static/chunks/commons*.module.js',
dest: 'next/static/chunks/commons.HASH.module.js'
dest: '.next/static/chunks/commons.HASH.module.js'
}
]
......
......@@ -12,7 +12,7 @@ const Comment = ({ data }) => (
)
Comment.getInitialProps = () => ({
data: typeof window === 'undefined' ? 'SSR' : 'Skeleton'
data: typeof window === 'undefined' ? 'SSR' : 'CSR'
})
export default Comment
......@@ -6,7 +6,7 @@ export const config = { experimentalPrerender: true }
export default class Post extends React.Component {
static async getInitialProps () {
return {
data: typeof window === 'undefined' ? 'SSR' : 'Skeleton'
data: typeof window === 'undefined' ? 'SSR' : 'CSR'
}
}
......
......@@ -105,14 +105,14 @@ const runTests = () => {
expect(html).not.toMatch(/Comment:.*?SSR/)
})
it('should call getInitialProps client-side when viewing skeleton', async () => {
it('should call getInitialProps 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/)
expect(text).toMatch(/Post:.*?SSR/)
await browser.close()
browser = await webdriver(
......@@ -121,7 +121,7 @@ const runTests = () => {
)
await waitFor(1000)
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Comment:.*?Skeleton/)
expect(text).toMatch(/Comment:.*?SSR/)
await browser.close()
})
}
......
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