Commit 92134905 authored by Tobias Koppers's avatar Tobias Koppers

integrate fallback app and error into client compiler

get rid of isDevFallback
parent caef3373
......@@ -229,7 +229,6 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling = false,
entrypoints,
rewrites,
isDevFallback = false,
runWebpackSpan,
}: {
buildId: string
......@@ -241,7 +240,6 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling?: boolean
entrypoints: webpack5.EntryObject
rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean
runWebpackSpan: Span
}
): Promise<webpack.Configuration> {
......@@ -889,7 +887,7 @@ export default async function getBaseWebpackConfig(
],
optimization: {
// @ts-ignore: TODO remove ts-ignore when webpack 4 is removed
emitOnErrors: !dev,
emitOnErrors: true,
checkWasmTypes: false,
nodeEnv: false,
splitChunks: isServer
......@@ -971,9 +969,7 @@ export default async function getBaseWebpackConfig(
? !dev
? '../[name].js'
: '[name].js'
: `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${
dev ? '' : '-[contenthash]'
}.js`,
: `static/chunks/[name]${dev ? '' : '-[contenthash]'}.js`,
library: isServer ? undefined : '_N_E',
libraryTarget: isServer ? 'commonjs2' : 'assign',
hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
......@@ -982,9 +978,7 @@ export default async function getBaseWebpackConfig(
// This saves chunks with the name given via `import()`
chunkFilename: isServer
? '[name].js'
: `static/chunks/${isDevFallback ? 'fallback/' : ''}${
dev ? '[name]' : '[name].[contenthash]'
}.js`,
: `static/chunks/${dev ? '[name]' : '[name].[contenthash]'}.js`,
strictModuleExceptionHandling: true,
crossOriginLoading: crossOrigin,
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
......@@ -1243,7 +1237,6 @@ export default async function getBaseWebpackConfig(
new BuildManifestPlugin({
buildId,
rewrites,
isDevFallback,
}),
new ProfilingPlugin({ runWebpackSpan }),
config.optimizeFonts &&
......
......@@ -92,15 +92,12 @@ const processRoute = (r: Rewrite) => {
export default class BuildManifestPlugin {
private buildId: string
private rewrites: CustomRoutes['rewrites']
private isDevFallback: boolean
constructor(options: {
buildId: string
rewrites: CustomRoutes['rewrites']
isDevFallback?: boolean
}) {
this.buildId = options.buildId
this.isDevFallback = !!options.isDevFallback
this.rewrites = {
beforeFiles: [],
afterFiles: [],
......@@ -189,50 +186,42 @@ export default class BuildManifestPlugin {
assetMap.pages[pagePath] = [...new Set([...mainFiles, ...filesForPage])]
}
if (!this.isDevFallback) {
// Add the runtime build manifest file (generated later in this file)
// as a dependency for the app. If the flag is false, the file won't be
// downloaded by the client.
assetMap.lowPriorityFiles.push(
`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
)
// Add the runtime ssg manifest file as a lazy-loaded file dependency.
// We also stub this file out for development mode (when it is not
// generated).
const srcEmptySsgManifest = `self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js`
assetMap.lowPriorityFiles.push(ssgManifestPath)
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest)
}
// Add the runtime build manifest file (generated later in this file)
// as a dependency for the app. If the flag is false, the file won't be
// downloaded by the client.
assetMap.lowPriorityFiles.push(
`${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
)
// Add the runtime ssg manifest file as a lazy-loaded file dependency.
// We also stub this file out for development mode (when it is not
// generated).
const srcEmptySsgManifest = `self.__SSG_MANIFEST=new Set;self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
const ssgManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_ssgManifest.js`
assetMap.lowPriorityFiles.push(ssgManifestPath)
assets[ssgManifestPath] = new sources.RawSource(srcEmptySsgManifest)
assetMap.pages = Object.keys(assetMap.pages)
.sort()
// eslint-disable-next-line
.reduce((a, c) => ((a[c] = assetMap.pages[c]), a), {} as any)
let buildManifestName = BUILD_MANIFEST
if (this.isDevFallback) {
buildManifestName = `fallback-${BUILD_MANIFEST}`
}
const buildManifestName = BUILD_MANIFEST
assets[buildManifestName] = new sources.RawSource(
JSON.stringify(assetMap, null, 2)
)
if (!this.isDevFallback) {
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
assets[clientManifestPath] = new sources.RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
compiler,
compilation,
assetMap,
this.rewrites
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
)
}
const clientManifestPath = `${CLIENT_STATIC_FILES_PATH}/${this.buildId}/_buildManifest.js`
assets[clientManifestPath] = new sources.RawSource(
`self.__BUILD_MANIFEST = ${generateClientManifest(
compiler,
compilation,
assetMap,
this.rewrites
)};self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`
)
return assets
})
......
......@@ -227,7 +227,7 @@ export default class HotReloader {
const page = denormalizePagePath(decodedPagePath)
if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) {
if (page === '/_error' || !BLOCKED_PAGES.includes(page)) {
try {
await this.ensurePage(page, true)
} catch (error) {
......@@ -238,10 +238,14 @@ export default class HotReloader {
return { finished: true }
}
const errors = await this.getCompilationErrors(page)
if (errors.length > 0) {
await renderScriptError(pageBundleRes, errors[0], { verbose: false })
return { finished: true }
if (!page.startsWith('/_fallback/')) {
const errors = await this.getCompilationErrors(page)
if (errors.length > 0) {
await renderScriptError(pageBundleRes, errors[0], {
verbose: false,
})
return { finished: true }
}
}
}
......@@ -345,52 +349,6 @@ export default class HotReloader {
})
}
public async buildFallbackError(): Promise<void> {
if (this.fallbackWatcher) return
const fallbackConfig = await getBaseWebpackConfig(this.dir, {
runWebpackSpan: this.hotReloaderSpan,
dev: true,
isServer: false,
config: this.config,
buildId: this.buildId,
pagesDir: this.pagesDir,
rewrites: {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
isDevFallback: true,
entrypoints: createEntrypoints(
{
'/_app': 'next/dist/pages/_app',
'/_error': 'next/dist/pages/_error',
},
'server',
this.buildId,
this.previewProps,
this.config,
[]
).client,
})
const fallbackCompiler = webpack(fallbackConfig)
this.fallbackWatcher = await new Promise((resolve) => {
let bootedFallbackCompiler = false
fallbackCompiler.watch(
// @ts-ignore webpack supports an array of watchOptions when using a multiCompiler
fallbackConfig.watchOptions,
// Errors are handled separately
(_err: any) => {
if (!bootedFallbackCompiler) {
bootedFallbackCompiler = true
resolve(true)
}
}
)
})
}
public async start(): Promise<void> {
const startSpan = this.hotReloaderSpan.traceChild('start')
startSpan.stop() // Stop immediately to create an artificial parent span
......@@ -411,13 +369,11 @@ export default class HotReloader {
Object.keys(entries).map(async (pageKey) => {
const isClientKey = pageKey.startsWith('client')
if (isClientKey !== isClientCompilation) return
const page = pageKey.slice(
isClientKey ? 'client'.length : 'server'.length
)
const { bundlePath, page, absolutePagePath, dispose } =
entries[pageKey]
if (isClientCompilation && page.match(API_ROUTE)) {
return
}
const { bundlePath, absolutePagePath, dispose } = entries[pageKey]
const pageExists = !dispose && (await isWriteable(absolutePagePath))
if (!pageExists) {
// page was removed or disposed
......@@ -433,7 +389,7 @@ export default class HotReloader {
if (isClientCompilation) {
entrypoints[bundlePath] = finalizeEntrypoint(
bundlePath,
page,
`next-client-pages-loader?${stringify(pageLoaderOpts)}!`,
false
)
......@@ -441,11 +397,7 @@ export default class HotReloader {
let request = relative(config.context!, absolutePagePath)
if (!isAbsolute(request) && !request.startsWith('../'))
request = `./${request}`
entrypoints[bundlePath] = finalizeEntrypoint(
bundlePath,
request,
true
)
entrypoints[bundlePath] = finalizeEntrypoint(page, request, true)
}
})
)
......@@ -699,16 +651,16 @@ export default class HotReloader {
public async ensurePage(page: string, clientOnly: boolean = false) {
// Make sure we don't re-build or dispose prebuilt pages
if (page !== '/_error' && BLOCKED_PAGES.indexOf(page) !== -1) {
if (page !== '/_error' && BLOCKED_PAGES.includes(page)) {
return
}
const error = clientOnly
? this.clientError
: this.serverError || this.clientError
if (error) {
return Promise.reject(error)
throw error
}
return this.onDemandEntries?.ensurePage(page, clientOnly) as any
await this.onDemandEntries?.ensurePage(page, clientOnly)
}
}
......
......@@ -754,10 +754,11 @@ export default class DevServer extends Server {
}
protected async getFallbackErrorComponents(): Promise<LoadComponentsReturnType | null> {
await this.hotReloader!.buildFallbackError()
// Build the error page to ensure the fallback is built too.
// TODO: See if this can be moved into hotReloader or removed.
await this.hotReloader!.ensurePage('/_error')
await Promise.all([
this.hotReloader!.ensurePage('/_fallback/_app', true),
this.hotReloader!.ensurePage('/_fallback/_error', true),
])
return await loadDefaultErrorComponents(this.distDir)
}
......
......@@ -16,6 +16,7 @@ export const BUILT = Symbol('built')
export let entries: {
[page: string]: {
bundlePath: string
page: string
absolutePagePath: string
status?: typeof ADDED | typeof BUILDING | typeof BUILT
lastActiveTime?: number
......@@ -155,11 +156,18 @@ export default function onDemandEntryHandler(
throw pageNotFoundError(page)
}
let pagePath = await findPageFile(
pagesDir,
normalizedPagePath,
pageExtensions
)
let pagePath
let overridePage: string | undefined = undefined
if (page.startsWith('/_fallback/')) {
overridePage = page.slice('/_fallback'.length)
pagePath = `next/dist/pages${overridePage}`
} else {
pagePath = await findPageFile(
pagesDir,
normalizedPagePath,
pageExtensions
)
}
// Default the /_error route to the Next.js provided default page
if (page === '/_error' && pagePath === null) {
......@@ -170,7 +178,7 @@ export default function onDemandEntryHandler(
throw pageNotFoundError(normalizedPagePath)
}
let pageUrl = pagePath.replace(/\\/g, '/')
let pageUrl = page.replace(/\\/g, '/')
pageUrl = `${pageUrl[0] !== '/' ? '/' : ''}${pageUrl
.replace(new RegExp(`\\.+(?:${pageExtensions.join('|')})$`), '')
......@@ -212,6 +220,7 @@ export default function onDemandEntryHandler(
entries[pageKey] = {
bundlePath,
page: overridePage || page,
absolutePagePath,
status: ADDED,
lastActiveTime: Date.now(),
......@@ -243,7 +252,7 @@ export default function onDemandEntryHandler(
invalidator.invalidate()
}
return promise
await promise
},
onHMR(client: ws) {
......
......@@ -43,12 +43,23 @@ export async function loadDefaultErrorComponents(distDir: string) {
const ComponentMod = require('next/dist/pages/_error')
const Component = interopDefault(ComponentMod)
const buildManifest: BuildManifest = require(join(distDir, BUILD_MANIFEST))
const fallbackBuildManifest = {
...buildManifest,
lowPriorityFiles: [],
pages: {
'/_app': buildManifest.pages['/_fallback/_app'],
'/_error': buildManifest.pages['/_fallback/_error'],
},
}
return {
App,
Document,
Component,
pageConfig: {},
buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)),
buildManifest: fallbackBuildManifest,
reactLoadableManifest: {},
ComponentMod,
}
......
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