Unverified Commit 6f90d196 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add route loader (#36712)

* Add route loader

* Update to leverage new view-loader

* fix lint
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 4fb0beb1
...@@ -285,6 +285,15 @@ export function getEdgeServerEntry(opts: { ...@@ -285,6 +285,15 @@ export function getEdgeServerEntry(opts: {
return `next-middleware-ssr-loader?${stringify(loaderParams)}!` return `next-middleware-ssr-loader?${stringify(loaderParams)}!`
} }
export function getViewsEntry(opts: { pagePath: string; viewsDir: string }) {
const loaderParams = {
pagePath: opts.pagePath,
viewsDir: opts.viewsDir,
}
return `next-view-loader?${stringify(loaderParams)}!`
}
export function getServerlessEntry(opts: { export function getServerlessEntry(opts: {
absolutePagePath: string absolutePagePath: string
buildId: string buildId: string
...@@ -357,6 +366,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -357,6 +366,11 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, isViews: boolean) => (mappings: Record<string, string>, isViews: boolean) =>
async (page: string) => { async (page: string) => {
// TODO: @timneutkens do not pass layouts to entry here
if (isViews && page.endsWith('/layout')) {
return
}
const bundleFile = normalizePagePath(page) const bundleFile = normalizePagePath(page)
const clientBundlePath = posix.join('pages', bundleFile) const clientBundlePath = posix.join('pages', bundleFile)
const serverBundlePath = posix.join( const serverBundlePath = posix.join(
...@@ -388,7 +402,12 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -388,7 +402,12 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}) })
}, },
onServer: () => { onServer: () => {
if (isTargetLikeServerless(target)) { if (isViews && viewsDir) {
server[serverBundlePath] = getViewsEntry({
pagePath: mappings[page],
viewsDir,
})
} else if (isTargetLikeServerless(target)) {
if (page !== '/_app' && page !== '/_document') { if (page !== '/_app' && page !== '/_document') {
server[serverBundlePath] = getServerlessEntry({ server[serverBundlePath] = getServerlessEntry({
...params, ...params,
......
import path from 'path'
import type webpack from 'webpack5' import type webpack from 'webpack5'
import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
function pathToUrlPath(pathname: string) {
let urlPath = pathname.replace(/^private-next-views-dir/, '')
// For `views/layout.js`
if (urlPath === '') {
urlPath = '/'
}
return urlPath
}
async function resolveLayoutPathsByPage({
pagePath,
resolve,
}: {
pagePath: string
resolve: (pathname: string) => Promise<string | undefined>
}) {
const layoutPaths = new Map<string, string | undefined>()
const parts = pagePath.split('/')
for (let i = 1; i < parts.length; i++) {
const pathWithoutSlashLayout = parts.slice(0, i).join('/')
const layoutPath = `${pathWithoutSlashLayout}/layout`
const resolvedLayoutPath = await resolve(layoutPath)
let urlPath = pathToUrlPath(pathWithoutSlashLayout)
layoutPaths.set(urlPath, resolvedLayoutPath)
}
return layoutPaths
}
const extensions = [
...NODE_RESOLVE_OPTIONS.extensions,
...NODE_RESOLVE_OPTIONS.extensions.map((ext) => `.server${ext}`),
...NODE_RESOLVE_OPTIONS.extensions.map((ext) => `.client${ext}`),
]
const resolveOptions: any = {
...NODE_RESOLVE_OPTIONS,
extensions,
}
const nextViewLoader: webpack.LoaderDefinitionFunction<{ const nextViewLoader: webpack.LoaderDefinitionFunction<{
components: string[] pagePath: string
}> = function nextViewLoader() { viewsDir: string
}> = async function nextViewLoader() {
const loaderOptions = this.getOptions() || {} const loaderOptions = this.getOptions() || {}
const resolve = this.getResolve(resolveOptions)
const viewsDir = loaderOptions.viewsDir
return ` const layoutPaths = await resolveLayoutPathsByPage({
export const components = { pagePath: loaderOptions.pagePath,
${loaderOptions.components resolve: async (pathname) => {
.map((component) => `'${component}': () => import('${component}')`) try {
.join(',\n')} return await resolve(this.rootContext, pathname)
} catch (err: any) {
if (err.message.includes("Can't resolve")) {
return undefined
}
throw err
}
},
})
const componentsCode = []
for (const [layoutPath, resolvedLayoutPath] of layoutPaths) {
if (resolvedLayoutPath) {
this.addDependency(resolvedLayoutPath)
// use require so that we can bust the require cache
const codeLine = `'${layoutPath}': () => require('${resolvedLayoutPath}')`
componentsCode.push(codeLine)
} else {
for (const ext of extensions) {
this.addMissingDependency(
path.join(viewsDir, layoutPath, `layout${ext}`)
)
}
}
} }
// Add page itself to the list of components
componentsCode.push(
`'${pathToUrlPath(loaderOptions.pagePath).replace(
new RegExp(`/page\\.+(${extensions.join('|')})$`),
''
// use require so that we can bust the require cache
)}': () => require('${loaderOptions.pagePath}')`
)
const result = `
export const components = {
${componentsCode.join(',\n')}
};
` `
return result
} }
export default nextViewLoader export default nextViewLoader
...@@ -1748,24 +1748,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1748,24 +1748,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return null return null
} }
const gatherViewLayouts = async (
viewPath: string,
result: FindComponentsResult
): Promise<void> => {
const layoutPaths = this.getViewPathLayouts(viewPath)
result.components.viewLayouts = await Promise.all(
layoutPaths.map(async (path) => {
const layoutRes = await this.findPageComponents(path)
return {
isRootLayout: path === '/layout',
Component: layoutRes?.components.Component!,
getStaticProps: layoutRes?.components.getStaticProps,
getServerSideProps: layoutRes?.components.getServerSideProps,
}
})
)
}
try { try {
// Ensure a request to the URL /accounts/[id] will be treated as a dynamic // Ensure a request to the URL /accounts/[id] will be treated as a dynamic
// route correctly and not loaded immediately without parsing params. // route correctly and not loaded immediately without parsing params.
...@@ -1778,9 +1760,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1778,9 +1760,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const result = await this.findPageComponents(page, query) const result = await this.findPageComponents(page, query)
if (result) { if (result) {
try { try {
if (result.components.isViewPath) {
await gatherViewLayouts(page, result)
}
return await this.renderToResponseWithComponents(ctx, result) return await this.renderToResponseWithComponents(ctx, result)
} catch (err) { } catch (err) {
const isNoFallbackError = err instanceof NoFallbackError const isNoFallbackError = err instanceof NoFallbackError
...@@ -1812,9 +1791,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1812,9 +1791,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) )
if (dynamicRouteResult) { if (dynamicRouteResult) {
try { try {
if (dynamicRouteResult.components.isViewPath) {
await gatherViewLayouts(page, dynamicRouteResult)
}
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
{ {
...ctx, ...ctx,
......
...@@ -11,11 +11,16 @@ import { ...@@ -11,11 +11,16 @@ import {
finalizeEntrypoint, finalizeEntrypoint,
getClientEntry, getClientEntry,
getEdgeServerEntry, getEdgeServerEntry,
getViewsEntry,
runDependingOnPageType, runDependingOnPageType,
} from '../../build/entries' } from '../../build/entries'
import { watchCompilers } from '../../build/output' import { watchCompilers } from '../../build/output'
import getBaseWebpackConfig from '../../build/webpack-config' import getBaseWebpackConfig from '../../build/webpack-config'
import { API_ROUTE, MIDDLEWARE_ROUTE } from '../../lib/constants' import {
API_ROUTE,
MIDDLEWARE_ROUTE,
VIEWS_DIR_ALIAS,
} from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { __ApiPreviewProps } from '../api-utils' import { __ApiPreviewProps } from '../api-utils'
...@@ -592,7 +597,16 @@ export default class HotReloader { ...@@ -592,7 +597,16 @@ export default class HotReloader {
entrypoints[bundlePath] = finalizeEntrypoint({ entrypoints[bundlePath] = finalizeEntrypoint({
compilerType: 'server', compilerType: 'server',
name: bundlePath, name: bundlePath,
value: request, value:
this.viewsDir && bundlePath.startsWith('views/')
? getViewsEntry({
pagePath: join(
VIEWS_DIR_ALIAS,
relative(this.viewsDir!, absolutePagePath)
),
viewsDir: this.viewsDir!,
})
: request,
}) })
} }
}, },
......
...@@ -41,12 +41,6 @@ export type LoadComponentsReturnType = { ...@@ -41,12 +41,6 @@ export type LoadComponentsReturnType = {
AppMod: any AppMod: any
AppServerMod: any AppServerMod: any
isViewPath?: boolean isViewPath?: boolean
viewLayouts?: Array<{
isRootLayout?: boolean
Component: NextComponentType
getStaticProps?: GetStaticProps
getServerSideProps?: GetServerSideProps
}>
} }
export async function loadDefaultErrorComponents(distDir: string) { export async function loadDefaultErrorComponents(distDir: string) {
......
...@@ -216,12 +216,12 @@ export async function renderToHTML( ...@@ -216,12 +216,12 @@ export async function renderToHTML(
const hasConcurrentFeatures = !!runtime const hasConcurrentFeatures = !!runtime
const pageIsDynamic = isDynamicRoute(pathname) const pageIsDynamic = isDynamicRoute(pathname)
const layouts = renderOpts.viewLayouts || [] const components = Object.keys(ComponentMod.components)
.sort()
layouts.push({ .map((key) => {
Component: renderOpts.Component, const mod = ComponentMod.components[key]()
getStaticProps: renderOpts.getStaticProps, mod.Component = mod.default || mod
getServerSideProps: renderOpts.getServerSideProps, return mod
}) })
// Reads of this are cached on the `req` object, so this should resolve // Reads of this are cached on the `req` object, so this should resolve
...@@ -239,11 +239,13 @@ export async function renderToHTML( ...@@ -239,11 +239,13 @@ export async function renderToHTML(
const dataCache = new Map<string, Record>() const dataCache = new Map<string, Record>()
for (let i = layouts.length - 1; i >= 0; i--) { for (let i = components.length - 1; i >= 0; i--) {
const dataCacheKey = i.toString() const dataCacheKey = i.toString()
const layout = layouts[i] const layout = components[i]
if (layout.isRootLayout) { if (i === 0) {
// top-most layout is the root layout that renders
// the html/body tags
RootLayout = layout.Component RootLayout = layout.Component
continue continue
} }
......
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