Skip to content

Commit

Permalink
node switchable app
Browse files Browse the repository at this point in the history
fix body render

fix loader cjs handling

manipulate _app for build and output

remove logs and add check for pages manifest plugin

fix _app.server resolving

revert test
  • Loading branch information
huozhi committed Mar 29, 2022
1 parent a00268e commit 46053ff
Show file tree
Hide file tree
Showing 16 changed files with 129 additions and 42 deletions.
27 changes: 24 additions & 3 deletions packages/next/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-lo
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import { LoadedEnvFiles } from '@next/env'
import { parse } from '../build/swc'
import { isCustomErrorPage, isFlightPage, isReservedPage } from './utils'
import {
getRawPageExtensions,
isCustomErrorPage,
isFlightPage,
isReservedPage,
} from './utils'
import { ssrEntries } from './webpack/plugins/middleware-plugin'
import {
MIDDLEWARE_RUNTIME_WEBPACK,
Expand All @@ -28,7 +33,14 @@ export type PagesMapping = {
}

export function getPageFromPath(pagePath: string, extensions: string[]) {
let page = pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '')
const rawExtensions = getRawPageExtensions(extensions)
const pickedExtensions = pagePath.includes('/_app.server.')
? rawExtensions
: extensions
let page = pagePath.replace(
new RegExp(`\\.+(${pickedExtensions.join('|')})$`),
''
)
page = page.replace(/\\/g, '/').replace(/\/index$/, '')
return page === '' ? '/' : page
}
Expand Down Expand Up @@ -85,10 +97,17 @@ export function createPagesMapping(
pages['/_app'] = `${PAGES_DIR_ALIAS}/_app`
pages['/_error'] = `${PAGES_DIR_ALIAS}/_error`
pages['/_document'] = `${PAGES_DIR_ALIAS}/_document`
if (hasServerComponents) {
pages['/_app.server'] = `${PAGES_DIR_ALIAS}/_app.server`
}
} else {
pages['/_app'] = pages['/_app'] || 'next/dist/pages/_app'
pages['/_error'] = pages['/_error'] || 'next/dist/pages/_error'
pages['/_document'] = pages['/_document'] || `next/dist/pages/_document`
if (hasServerComponents) {
pages['/_app.server'] =
pages['/_app.server'] || 'next/dist/pages/_app.server'
}
}
return pages
}
Expand Down Expand Up @@ -220,6 +239,7 @@ export async function createEntrypoints(

const defaultServerlessOptions = {
absoluteAppPath: pages['/_app'],
absoluteAppServerPath: pages['/_app.server'],
absoluteDocumentPath: pages['/_document'],
absoluteErrorPath: pages['/_error'],
absolute404Path: pages['/404'] || '',
Expand Down Expand Up @@ -312,6 +332,7 @@ export async function createEntrypoints(
} else if (
isLikeServerless &&
page !== '/_app' &&
page !== '/_app.server' &&
page !== '/_document' &&
!isEdgeRuntime
) {
Expand All @@ -325,7 +346,7 @@ export async function createEntrypoints(
)}!`
}

if (page === '/_document') {
if (page === '/_document' || page === '/_app.server') {
return
}

Expand Down
1 change: 1 addition & 0 deletions packages/next/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ export async function printTreeView(
!(
e === '/_document' ||
e === '/_error' ||
e === '/_app.server' ||
(!hasCustomApp && e === '/_app')
)
)
Expand Down
9 changes: 8 additions & 1 deletion packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,12 +554,19 @@ export default async function getBaseWebpackConfig(

if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...config.pageExtensions.reduce((prev, ext) => {
...rawPageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_app.server`] = [
...rawPageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.server.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.server.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_error.${ext}`))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default async function middlewareSSRLoader(this: any) {
buildId,
absolutePagePath,
absoluteAppPath,
absoluteAppServerPath,
absoluteDocumentPath,
absolute500Path,
absoluteErrorPath,
Expand All @@ -16,6 +17,8 @@ export default async function middlewareSSRLoader(this: any) {

const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest(this, absoluteAppPath)
const stringifiedAppServerPath = stringifyRequest(this, absoluteAppServerPath)

const stringifiedErrorPath = stringifyRequest(this, absoluteErrorPath)
const stringifiedDocumentPath = stringifyRequest(this, absoluteDocumentPath)
const stringified500Path = absolute500Path
Expand All @@ -31,6 +34,7 @@ export default async function middlewareSSRLoader(this: any) {
import Document from ${stringifiedDocumentPath}
const appMod = require(${stringifiedAppPath})
const appServerMod = require(${stringifiedAppServerPath})
const pageMod = require(${stringifiedPagePath})
const errorMod = require(${stringifiedErrorPath})
const error500Mod = ${stringified500Path} ? require(${stringified500Path}) : null
Expand All @@ -56,6 +60,8 @@ export default async function middlewareSSRLoader(this: any) {
buildManifest,
reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
appServerMod: appServerMod,
isServerComponent: ${isServerComponent},
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function getRender({
serverComponentManifest,
config,
buildId,
appServerMod,
}: {
dev: boolean
page: string
Expand All @@ -37,7 +38,9 @@ export function getRender({
Document: DocumentType
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
serverComponentManifest: any | null
serverComponentManifest: any
appServerMod: any
isServerComponent: boolean
config: NextConfig
buildId: string
}) {
Expand All @@ -48,6 +51,7 @@ export function getRender({
Document,
App: appMod.default as AppType,
AppMod: appMod,
AppServerMod: appServerMod,
}

const server = new WebServer({
Expand Down
4 changes: 4 additions & 0 deletions packages/next/build/webpack/plugins/pages-manifest-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ export default class PagesManifestPlugin implements webpack.Plugin {
file.endsWith('.js')
)

// Skip _app.server entry which is empty
if (!files.length) {
continue
}
// Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
pages[pagePath] = files[files.length - 1]

Expand Down
5 changes: 4 additions & 1 deletion packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ let webpackHMR: any
let CachedApp: AppComponent, onPerfEntry: (metric: any) => void
let CachedComponent: React.ComponentType
let isAppRSC: boolean
let isRSCPage: boolean

class Container extends React.Component<{
fn: (err: Error, info?: any) => void
Expand Down Expand Up @@ -333,6 +334,7 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) {
throw pageEntrypoint.error
}
CachedComponent = pageEntrypoint.component
isRSCPage = !!pageEntrypoint.exports.__next_rsc__

if (process.env.NODE_ENV !== 'production') {
const { isValidElementType } = require('next/dist/compiled/react-is')
Expand Down Expand Up @@ -646,7 +648,8 @@ function AppContainer({
}

function renderApp(App: AppComponent, appProps: AppProps) {
if (process.env.__NEXT_RSC && isAppRSC) {
console.log('isRSCPage', isRSCPage)
if (process.env.__NEXT_RSC && isRSCPage) {
const { Component, err: _, router: __, ...props } = appProps
return <Component {...props} />
} else {
Expand Down
7 changes: 6 additions & 1 deletion packages/next/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ export default async function exportApp(
continue
}

if (page === '/_document' || page === '/_app' || page === '/_error') {
if (
page === '/_document' ||
page === '/_app.server' ||
page === '/_app' ||
page === '/_error'
) {
continue
}

Expand Down
6 changes: 6 additions & 0 deletions packages/next/pages/_app.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from 'react'

export type AppProps = { children: React.ReactNode }
export default function AppServer({ children }: AppProps) {
return children
}
1 change: 1 addition & 0 deletions packages/next/server/dev/hot-reloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ export default class HotReloader {
page,
stringifiedConfig: JSON.stringify(this.config),
absoluteAppPath: this.pagesMapping['/_app'],
absoluteAppServerPath: this.pagesMapping['/_app.server'],
absoluteDocumentPath: this.pagesMapping['/_document'],
absoluteErrorPath: this.pagesMapping['/_error'],
absolute404Path: this.pagesMapping['/404'] || '',
Expand Down
5 changes: 4 additions & 1 deletion packages/next/server/dev/next-dev-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,7 @@ export default class DevServer extends Server {
}
}

console.error(err)
if (!usedOriginalStack) {
if (type === 'warning') {
Log.warn(err + '')
Expand Down Expand Up @@ -937,9 +938,11 @@ export default class DevServer extends Server {
try {
await this.hotReloader!.ensurePage(pathname)

const serverComponents = this.nextConfig.experimental.serverComponents

// When the new page is compiled, we need to reload the server component
// manifest.
if (this.nextConfig.experimental.serverComponents) {
if (serverComponents) {
this.serverComponentManifest = super.getServerComponentManifest()
}

Expand Down
9 changes: 7 additions & 2 deletions packages/next/server/load-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ export type LoadComponentsReturnType = {
pageConfig: PageConfig
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
serverComponentManifest?: any | null
serverComponentManifest?: any
Document: DocumentType
App: AppType
getStaticProps?: GetStaticProps
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
ComponentMod: any
AppMod: any
AppServerMod: any
}

export async function loadDefaultErrorComponents(distDir: string) {
Expand All @@ -57,6 +58,8 @@ export async function loadDefaultErrorComponents(distDir: string) {
reactLoadableManifest: {},
ComponentMod,
AppMod,
// TODO detect server components
AppServerMod: AppMod,
}
}

Expand Down Expand Up @@ -99,10 +102,11 @@ export async function loadComponents(
} as LoadComponentsReturnType
}

const [DocumentMod, AppMod, ComponentMod] = await Promise.all([
const [DocumentMod, AppMod, ComponentMod, AppServerMod] = await Promise.all([
requirePage('/_document', distDir, serverless),
requirePage('/_app', distDir, serverless),
requirePage(pathname, distDir, serverless),
serverComponents ? requirePage('/_app.server', distDir, serverless) : null,
])

const [buildManifest, reactLoadableManifest, serverComponentManifest] =
Expand All @@ -129,6 +133,7 @@ export async function loadComponents(
pageConfig: ComponentMod.config || {},
ComponentMod,
AppMod,
AppServerMod,
getServerSideProps,
getStaticProps,
getStaticPaths,
Expand Down
3 changes: 2 additions & 1 deletion packages/next/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,8 @@ export default class NextNodeServer extends BaseServer {
const components = await loadComponents(
this.distDir,
pagePath!,
!this.renderOpts.dev && this._isLikeServerless
!this.renderOpts.dev && this._isLikeServerless,
this.renderOpts.serverComponents
)

if (
Expand Down
Loading

0 comments on commit 46053ff

Please sign in to comment.