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