Unverified Commit 0c494af9 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Use absolute document and app paths for the middleware SSR loader (#30963)

* use absolute path

* use absolute path

* update test

* rename modern -> web
Co-authored-by: 's avatarShu Ding <g@shud.in>
parent 9da6cf25
...@@ -18,7 +18,7 @@ import type { webpack5 } from 'next/dist/compiled/webpack/webpack' ...@@ -18,7 +18,7 @@ import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { MIDDLEWARE_SSR_RUNTIME_WEBPACK } from '../shared/lib/constants' import { MIDDLEWARE_SSR_RUNTIME_WEBPACK } from '../shared/lib/constants'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
type PagesMapping = { export type PagesMapping = {
[page: string]: string [page: string]: string
} }
...@@ -65,6 +65,7 @@ export function createPagesMapping( ...@@ -65,6 +65,7 @@ export function createPagesMapping(
// we alias these in development and allow webpack to // we alias these in development and allow webpack to
// allow falling back to the correct source file so // allow falling back to the correct source file so
// that HMR can work properly when a file is added/removed // that HMR can work properly when a file is added/removed
const documentPage = `_document${hasServerComponents ? '.web' : ''}`
if (isDev) { if (isDev) {
pages['/_app'] = `${PAGES_DIR_ALIAS}/_app` pages['/_app'] = `${PAGES_DIR_ALIAS}/_app`
pages['/_error'] = `${PAGES_DIR_ALIAS}/_error` pages['/_error'] = `${PAGES_DIR_ALIAS}/_error`
...@@ -72,7 +73,8 @@ export function createPagesMapping( ...@@ -72,7 +73,8 @@ export function createPagesMapping(
} else { } else {
pages['/_app'] = pages['/_app'] || 'next/dist/pages/_app' pages['/_app'] = pages['/_app'] || 'next/dist/pages/_app'
pages['/_error'] = pages['/_error'] || 'next/dist/pages/_error' pages['/_error'] = pages['/_error'] || 'next/dist/pages/_error'
pages['/_document'] = pages['/_document'] || 'next/dist/pages/_document' pages['/_document'] =
pages['/_document'] || `next/dist/pages/${documentPage}`
} }
return pages return pages
} }
...@@ -159,6 +161,8 @@ export function createEntrypoints( ...@@ -159,6 +161,8 @@ export function createEntrypoints(
name: '[name].js', name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({ value: `next-middleware-ssr-loader?${stringify({
page, page,
absoluteAppPath: pages['/_app'],
absoluteDocumentPath: pages['/_document'],
absolutePagePath, absolutePagePath,
isServerComponent: isFlight, isServerComponent: isFlight,
buildId, buildId,
......
...@@ -629,7 +629,7 @@ export default async function getBaseWebpackConfig( ...@@ -629,7 +629,7 @@ export default async function getBaseWebpackConfig(
prev.push(path.join(pagesDir, `_document.${ext}`)) prev.push(path.join(pagesDir, `_document.${ext}`))
return prev return prev
}, [] as string[]), }, [] as string[]),
'next/dist/pages/_document.js', `next/dist/pages/_document${hasServerComponents ? '.web' : ''}.js`,
] ]
} }
......
import { getStringifiedAbsolutePath } from './utils'
import { stringifyRequest } from '../../stringify-request' import { stringifyRequest } from '../../stringify-request'
const fallbackDocumentPage = `
import { Html, Head, Main, NextScript } from 'next/document'
function Document() {
return (
createElement(Html, null,
createElement(Head),
createElement('body', null,
createElement(Main),
createElement(NextScript),
)
)
)
}
`
function hasModule(path: string) {
let has
try {
has = !!require.resolve(path)
} catch (_) {
has = false
}
return has
}
export default async function middlewareRSCLoader(this: any) { export default async function middlewareRSCLoader(this: any) {
const { const {
absolutePagePath, absolutePagePath,
absoluteAppPath,
absoluteDocumentPath,
basePath, basePath,
isServerComponent: isServerComponentQuery, isServerComponent: isServerComponentQuery,
assetPrefix, assetPrefix,
...@@ -38,31 +13,14 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -38,31 +13,14 @@ export default async function middlewareRSCLoader(this: any) {
const isServerComponent = isServerComponentQuery === 'true' const isServerComponent = isServerComponentQuery === 'true'
const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath) const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAbsoluteDocumentPath = getStringifiedAbsolutePath( const stringifiedAbsoluteAppPath = stringifyRequest(this, absoluteAppPath)
const stringifiedAbsoluteDocumentPath = stringifyRequest(
this, this,
'./pages/_document' absoluteDocumentPath
) )
const stringifiedAbsoluteAppPath = getStringifiedAbsolutePath(
this,
'./pages/_app'
)
const hasProvidedAppPage = hasModule(
this.utils.absolutify(this.rootContext, './pages/_app')
)
const hasProvidedDocumentPage = hasModule(
this.utils.absolutify(this.rootContext, './pages/_document')
)
let appDefinition = `const App = require(${
hasProvidedAppPage
? stringifiedAbsoluteAppPath
: JSON.stringify('next/dist/pages/_app')
}).default`
let documentDefinition = hasProvidedDocumentPage let appDefinition = `const App = require(${stringifiedAbsoluteAppPath}).default`
? `const Document = require(${stringifiedAbsoluteDocumentPath}).default` let documentDefinition = `const Document = require(${stringifiedAbsoluteDocumentPath}).default`
: fallbackDocumentPage
const transformed = ` const transformed = `
import { adapter } from 'next/dist/server/web/adapter' import { adapter } from 'next/dist/server/web/adapter'
...@@ -80,8 +38,8 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -80,8 +38,8 @@ export default async function middlewareRSCLoader(this: any) {
: '' : ''
} }
${documentDefinition}
${appDefinition} ${appDefinition}
${documentDefinition}
const { const {
default: Page, default: Page,
......
import React from 'react'
import { Html, Head, Main, NextScript } from './_document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
createEntrypoints, createEntrypoints,
createPagesMapping, createPagesMapping,
finalizeEntrypoint, finalizeEntrypoint,
PagesMapping,
} 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'
...@@ -156,6 +157,7 @@ export default class HotReloader { ...@@ -156,6 +157,7 @@ export default class HotReloader {
private rewrites: CustomRoutes['rewrites'] private rewrites: CustomRoutes['rewrites']
private fallbackWatcher: any private fallbackWatcher: any
private hotReloaderSpan: Span private hotReloaderSpan: Span
private pagesMapping: PagesMapping = {}
constructor( constructor(
dir: string, dir: string,
...@@ -305,7 +307,7 @@ export default class HotReloader { ...@@ -305,7 +307,7 @@ export default class HotReloader {
]) ])
) )
const pages = webpackConfigSpan this.pagesMapping = webpackConfigSpan
.traceChild('create-pages-mapping') .traceChild('create-pages-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping( createPagesMapping(
...@@ -315,11 +317,12 @@ export default class HotReloader { ...@@ -315,11 +317,12 @@ export default class HotReloader {
this.hasServerComponents this.hasServerComponents
) )
) )
const entrypoints = webpackConfigSpan const entrypoints = webpackConfigSpan
.traceChild('create-entrypoints') .traceChild('create-entrypoints')
.traceFn(() => .traceFn(() =>
createEntrypoints( createEntrypoints(
pages, this.pagesMapping,
'server', 'server',
this.buildId, this.buildId,
this.previewProps, this.previewProps,
...@@ -513,6 +516,8 @@ export default class HotReloader { ...@@ -513,6 +516,8 @@ export default class HotReloader {
name: '[name].js', name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({ value: `next-middleware-ssr-loader?${stringify({
page, page,
absoluteAppPath: this.pagesMapping['/_app'],
absoluteDocumentPath: this.pagesMapping['/_document'],
absolutePagePath, absolutePagePath,
isServerComponent, isServerComponent,
buildId: this.buildId, buildId: this.buildId,
......
...@@ -1121,8 +1121,18 @@ export async function pages_document(task, opts) { ...@@ -1121,8 +1121,18 @@ export async function pages_document(task, opts) {
.target('dist/pages') .target('dist/pages')
} }
export async function pages_document_server(task, opts) {
await task
.source('pages/_document.web.tsx')
.swc('client', { dev: opts.dev })
.target('dist/pages')
}
export async function pages(task, opts) { export async function pages(task, opts) {
await task.parallel(['pages_app', 'pages_error', 'pages_document'], opts) await task.parallel(
['pages_app', 'pages_error', 'pages_document', 'pages_document_server'],
opts
)
} }
export async function telemetry(task, opts) { export async function telemetry(task, opts) {
......
...@@ -21,7 +21,7 @@ const nodeArgs = ['-r', join(__dirname, '../../react-18/test/require-hook.js')] ...@@ -21,7 +21,7 @@ const nodeArgs = ['-r', join(__dirname, '../../react-18/test/require-hook.js')]
const appDir = join(__dirname, '../app') const appDir = join(__dirname, '../app')
const nativeModuleTestAppDir = join(__dirname, '../unsupported-native-module') const nativeModuleTestAppDir = join(__dirname, '../unsupported-native-module')
const distDir = join(__dirname, '../app/.next') const distDir = join(__dirname, '../app/.next')
const documentPage = new File(join(appDir, 'pages/_document.js')) const documentPage = new File(join(appDir, 'pages/_document.jsx'))
const appPage = new File(join(appDir, 'pages/_app.js')) const appPage = new File(join(appDir, 'pages/_app.js'))
const documentWithGip = ` const documentWithGip = `
......
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