Unverified Commit 295f9da3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Client directive (#40415)

## Feature
Change server components convention from using `.server.js` / `.client.js` file extension to determine it's a server or client component to using `'client'` js literal as a directive for determine client components boundary.
React RFC: https://github.com/reactjs/rfcs/pull/189
New behavior doesn't consume `.server.js` as server components any more, if you're enabling `serverComponents` flag, every `page.js` in app dir will become server components by default. If you adding a `'client'` directive to the page, then that page will become a client component. This rule also applies to the normal js components, client components will require a `'client'` directive to indicate its identity, instead of having a `.client.js` extension.
- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`
Co-authored-by: 's avatarShu Ding <3676859+shuding@users.noreply.github.com>
parent f0ed328b
...@@ -13,6 +13,7 @@ import { SERVER_RUNTIME } from '../../lib/constants' ...@@ -13,6 +13,7 @@ import { SERVER_RUNTIME } from '../../lib/constants'
import { ServerRuntime } from 'next/types' import { ServerRuntime } from 'next/types'
import { checkCustomRoutes } from '../../lib/load-custom-routes' import { checkCustomRoutes } from '../../lib/load-custom-routes'
import { matcher } from 'next/dist/compiled/micromatch' import { matcher } from 'next/dist/compiled/micromatch'
import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
export interface MiddlewareConfig { export interface MiddlewareConfig {
matchers: MiddlewareMatcher[] matchers: MiddlewareMatcher[]
...@@ -29,9 +30,18 @@ export interface PageStaticInfo { ...@@ -29,9 +30,18 @@ export interface PageStaticInfo {
runtime?: ServerRuntime runtime?: ServerRuntime
ssg?: boolean ssg?: boolean
ssr?: boolean ssr?: boolean
rsc?: RSCModuleType
middleware?: Partial<MiddlewareConfig> middleware?: Partial<MiddlewareConfig>
} }
const CLIENT_MODULE_LABEL = `/* __next_internal_client_entry_do_not_use__ */`
export type RSCModuleType = 'server' | 'client'
export function getRSCModuleType(source: string): RSCModuleType {
return source.includes(CLIENT_MODULE_LABEL)
? RSC_MODULE_TYPES.client
: RSC_MODULE_TYPES.server
}
/** /**
* Receives a parsed AST from SWC and checks if it belongs to a module that * Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are: * requires a runtime to be specified. Those are:
...@@ -252,6 +262,7 @@ export async function getPageStaticInfo(params: { ...@@ -252,6 +262,7 @@ export async function getPageStaticInfo(params: {
) { ) {
const swcAST = await parseModule(pageFilePath, fileContent) const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr } = checkExports(swcAST) const { ssg, ssr } = checkExports(swcAST)
const rsc = getRSCModuleType(fileContent)
// default / failsafe value for config // default / failsafe value for config
let config: any = {} let config: any = {}
...@@ -303,10 +314,16 @@ export async function getPageStaticInfo(params: { ...@@ -303,10 +314,16 @@ export async function getPageStaticInfo(params: {
return { return {
ssr, ssr,
ssg, ssg,
rsc,
...(middlewareConfig && { middleware: middlewareConfig }), ...(middlewareConfig && { middleware: middlewareConfig }),
...(runtime && { runtime }), ...(runtime && { runtime }),
} }
} }
return { ssr: false, ssg: false, runtime: nextConfig.experimental?.runtime } return {
ssr: false,
ssg: false,
rsc: RSC_MODULE_TYPES.server,
runtime: nextConfig.experimental?.runtime,
}
} }
...@@ -21,6 +21,7 @@ import { ...@@ -21,6 +21,7 @@ import {
SERVER_RUNTIME, SERVER_RUNTIME,
WEBPACK_LAYERS, WEBPACK_LAYERS,
} from '../lib/constants' } from '../lib/constants'
import { RSC_MODULE_TYPES } from '../shared/lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -37,14 +38,12 @@ import { warn } from './output/log' ...@@ -37,14 +38,12 @@ import { warn } from './output/log'
import { import {
isMiddlewareFile, isMiddlewareFile,
isMiddlewareFilename, isMiddlewareFilename,
isServerComponentPage,
NestedMiddlewareError, NestedMiddlewareError,
MiddlewareInServerlessTargetError, MiddlewareInServerlessTargetError,
} from './utils' } from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info' import { getPageStaticInfo } from './analysis/get-page-static-info'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { serverComponentRegex } from './webpack/loaders/utils'
import { ServerRuntime } from '../types' import { ServerRuntime } from '../types'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader' import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
...@@ -66,14 +65,12 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) { ...@@ -66,14 +65,12 @@ export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
} }
export function createPagesMapping({ export function createPagesMapping({
hasServerComponents,
isDev, isDev,
pageExtensions, pageExtensions,
pagePaths, pagePaths,
pagesType, pagesType,
pagesDir, pagesDir,
}: { }: {
hasServerComponents: boolean
isDev: boolean isDev: boolean
pageExtensions: string[] pageExtensions: string[]
pagePaths: string[] pagePaths: string[]
...@@ -90,13 +87,6 @@ export function createPagesMapping({ ...@@ -90,13 +87,6 @@ export function createPagesMapping({
const pageKey = getPageFromPath(pagePath, pageExtensions) const pageKey = getPageFromPath(pagePath, pageExtensions)
// Assume that if there's a Client Component, that there is
// a matching Server Component that will map to the page.
// so we will not process it
if (hasServerComponents && /\.client$/.test(pageKey)) {
return result
}
if (pageKey in result) { if (pageKey in result) {
warn( warn(
`Duplicate page detected. ${chalk.cyan( `Duplicate page detected. ${chalk.cyan(
...@@ -208,10 +198,7 @@ export function getEdgeServerEntry(opts: { ...@@ -208,10 +198,7 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
buildId: opts.buildId, buildId: opts.buildId,
dev: opts.isDev, dev: opts.isDev,
isServerComponent: isServerComponentPage( isServerComponent: opts.isServerComponent,
opts.config,
opts.absolutePagePath
),
page: opts.page, page: opts.page,
stringifiedConfig: JSON.stringify(opts.config), stringifiedConfig: JSON.stringify(opts.config),
pagesType: opts.pagesType, pagesType: opts.pagesType,
...@@ -418,8 +405,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -418,8 +405,10 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
nestedMiddleware.push(page) nestedMiddleware.push(page)
} }
const isServerComponent = serverComponentRegex.test(absolutePagePath) const isInsideAppDir =
const isInsideAppDir = appDir && absolutePagePath.startsWith(appDir) !!appDir &&
(absolutePagePath.startsWith(APP_DIR_ALIAS) ||
absolutePagePath.startsWith(appDir))
const staticInfo = await getPageStaticInfo({ const staticInfo = await getPageStaticInfo({
nextConfig: config, nextConfig: config,
...@@ -428,6 +417,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -428,6 +417,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
page, page,
}) })
const isServerComponent =
isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client
if (isMiddlewareFile(page)) { if (isMiddlewareFile(page)) {
middlewareMatchers = staticInfo.middleware?.matchers ?? [ middlewareMatchers = staticInfo.middleware?.matchers ?? [
{ regexp: '.*' }, { regexp: '.*' },
......
...@@ -58,6 +58,7 @@ import { ...@@ -58,6 +58,7 @@ import {
COMPILER_NAMES, COMPILER_NAMES,
APP_BUILD_MANIFEST, APP_BUILD_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST, FLIGHT_SERVER_CSS_MANIFEST,
RSC_MODULE_TYPES,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils' import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
...@@ -96,7 +97,6 @@ import { ...@@ -96,7 +97,6 @@ import {
printTreeView, printTreeView,
copyTracedFiles, copyTracedFiles,
isReservedPage, isReservedPage,
isServerComponentPage,
} from './utils' } from './utils'
import getBaseWebpackConfig from './webpack-config' import getBaseWebpackConfig from './webpack-config'
import { PagesManifest } from './webpack/plugins/pages-manifest-plugin' import { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
...@@ -489,7 +489,6 @@ export default async function build( ...@@ -489,7 +489,6 @@ export default async function build(
.traceChild('create-pages-mapping') .traceChild('create-pages-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping({ createPagesMapping({
hasServerComponents,
isDev: false, isDev: false,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
pagesType: 'pages', pagesType: 'pages',
...@@ -506,7 +505,6 @@ export default async function build( ...@@ -506,7 +505,6 @@ export default async function build(
.traceFn(() => .traceFn(() =>
createPagesMapping({ createPagesMapping({
pagePaths: appPaths!, pagePaths: appPaths!,
hasServerComponents,
isDev: false, isDev: false,
pagesType: 'app', pagesType: 'app',
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
...@@ -518,7 +516,6 @@ export default async function build( ...@@ -518,7 +516,6 @@ export default async function build(
let mappedRootPaths: { [page: string]: string } = {} let mappedRootPaths: { [page: string]: string } = {}
if (rootPaths.length > 0) { if (rootPaths.length > 0) {
mappedRootPaths = createPagesMapping({ mappedRootPaths = createPagesMapping({
hasServerComponents,
isDev: false, isDev: false,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
pagePaths: rootPaths, pagePaths: rootPaths,
...@@ -1267,21 +1264,17 @@ export default async function build( ...@@ -1267,21 +1264,17 @@ export default async function build(
) )
: appPaths?.find((p) => p.startsWith(actualPage + '/page.')) : appPaths?.find((p) => p.startsWith(actualPage + '/page.'))
const pageRuntime = const staticInfo =
pagesDir && pageType === 'pages' && pagePath pagesDir && pageType === 'pages' && pagePath
? ( ? await getPageStaticInfo({
await getPageStaticInfo({ pageFilePath: join(pagesDir, pagePath),
pageFilePath: join(pagesDir, pagePath), nextConfig: config,
nextConfig: config, })
}) : {}
).runtime const pageRuntime = staticInfo.runtime
: undefined isServerComponent =
pageType === 'app' &&
if (hasServerComponents && pagePath) { staticInfo.rsc !== RSC_MODULE_TYPES.client
if (isServerComponentPage(config, pagePath)) {
isServerComponent = true
}
}
if ( if (
// Only calculate page static information if the page is not an // Only calculate page static information if the page is not an
......
...@@ -1327,33 +1327,6 @@ export function detectConflictingPaths( ...@@ -1327,33 +1327,6 @@ export function detectConflictingPaths(
} }
} }
/**
* With RSC we automatically add .server and .client to page extensions. This
* function allows to remove them for cases where we just need to strip out
* the actual extension keeping the .server and .client.
*/
export function withoutRSCExtensions(pageExtensions: string[]): string[] {
return pageExtensions.filter(
(ext) => !ext.startsWith('client.') && !ext.startsWith('server.')
)
}
export function isServerComponentPage(
nextConfig: NextConfigComplete,
filePath: string
): boolean {
if (!nextConfig.experimental.serverComponents) {
return false
}
const rawPageExtensions = withoutRSCExtensions(
nextConfig.pageExtensions || []
)
return rawPageExtensions.some((ext) => {
return filePath.endsWith(`.server.${ext}`)
})
}
export async function copyTracedFiles( export async function copyTracedFiles(
dir: string, dir: string,
distDir: string, distDir: string,
......
...@@ -56,7 +56,6 @@ import type { ...@@ -56,7 +56,6 @@ import type {
} from './webpack/plugins/telemetry-plugin' } from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace' import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info' import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import { withoutRSCExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist' import browserslist from 'next/dist/compiled/browserslist'
import loadJsConfig from './load-jsconfig' import loadJsConfig from './load-jsconfig'
import { loadBindings } from './swc' import { loadBindings } from './swc'
...@@ -687,13 +686,7 @@ export default async function getBaseWebpackConfig( ...@@ -687,13 +686,7 @@ export default async function getBaseWebpackConfig(
babel: getBabelOrSwcLoader(), babel: getBabelOrSwcLoader(),
} }
const rawPageExtensions = hasServerComponents const pageExtensions = config.pageExtensions
? withoutRSCExtensions(config.pageExtensions)
: config.pageExtensions
const serverComponentsRegex = new RegExp(
`\\.server\\.(${rawPageExtensions.join('|')})$`
)
const babelIncludeRegexes: RegExp[] = [ const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/]shared[\\/]lib/, /next[\\/]dist[\\/]shared[\\/]lib/,
...@@ -801,7 +794,7 @@ export default async function getBaseWebpackConfig( ...@@ -801,7 +794,7 @@ export default async function getBaseWebpackConfig(
if (dev) { if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [ customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...(pagesDir ...(pagesDir
? rawPageExtensions.reduce((prev, ext) => { ? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.${ext}`)) prev.push(path.join(pagesDir, `_app.${ext}`))
return prev return prev
}, [] as string[]) }, [] as string[])
...@@ -810,7 +803,7 @@ export default async function getBaseWebpackConfig( ...@@ -810,7 +803,7 @@ export default async function getBaseWebpackConfig(
] ]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [ customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...(pagesDir ...(pagesDir
? rawPageExtensions.reduce((prev, ext) => { ? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_error.${ext}`)) prev.push(path.join(pagesDir, `_error.${ext}`))
return prev return prev
}, [] as string[]) }, [] as string[])
...@@ -819,7 +812,7 @@ export default async function getBaseWebpackConfig( ...@@ -819,7 +812,7 @@ export default async function getBaseWebpackConfig(
] ]
customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [ customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [
...(pagesDir ...(pagesDir
? rawPageExtensions.reduce((prev, ext) => { ? pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_document.${ext}`)) prev.push(path.join(pagesDir, `_document.${ext}`))
return prev return prev
}, [] as string[]) }, [] as string[])
...@@ -874,7 +867,7 @@ export default async function getBaseWebpackConfig( ...@@ -874,7 +867,7 @@ export default async function getBaseWebpackConfig(
...getReactProfilingInProduction(), ...getReactProfilingInProduction(),
[RSC_MOD_REF_PROXY_ALIAS]: [RSC_MOD_REF_PROXY_ALIAS]:
'next/dist/build/webpack/loaders/next-flight-client-loader/module-proxy', 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy',
...(isClient || isEdgeServer ...(isClient || isEdgeServer
? { ? {
...@@ -1151,11 +1144,6 @@ export default async function getBaseWebpackConfig( ...@@ -1151,11 +1144,6 @@ export default async function getBaseWebpackConfig(
}, },
} }
const serverComponentCodeCondition = {
test: serverComponentsRegex,
include: [dir, /next[\\/]dist[\\/]pages/],
}
const rscSharedRegex = const rscSharedRegex =
/(node_modules\/react\/|\/shared\/lib\/(head-manager-context|router-context|flush-effects)\.js|node_modules\/styled-jsx\/)/ /(node_modules\/react\/|\/shared\/lib\/(head-manager-context|router-context|flush-effects)\.js|node_modules\/styled-jsx\/)/
...@@ -1451,8 +1439,7 @@ export default async function getBaseWebpackConfig( ...@@ -1451,8 +1439,7 @@ export default async function getBaseWebpackConfig(
'next-image-loader', 'next-image-loader',
'next-serverless-loader', 'next-serverless-loader',
'next-style-loader', 'next-style-loader',
'next-flight-client-loader', 'next-flight-loader',
'next-flight-server-loader',
'next-flight-client-entry-loader', 'next-flight-client-entry-loader',
'noop-loader', 'noop-loader',
'next-middleware-loader', 'next-middleware-loader',
...@@ -1492,24 +1479,17 @@ export default async function getBaseWebpackConfig( ...@@ -1492,24 +1479,17 @@ export default async function getBaseWebpackConfig(
? [ ? [
// RSC server compilation loaders // RSC server compilation loaders
{ {
...serverComponentCodeCondition, test: codeCondition.test,
include: [
dir,
// To let the internal client components passing through flight loader
/next[\\/]dist[\\/]client[\\/]/,
],
issuerLayer: WEBPACK_LAYERS.server, issuerLayer: WEBPACK_LAYERS.server,
use: { use: {
loader: 'next-flight-server-loader', loader: 'next-flight-loader',
}, },
}, },
// {
// test: clientComponentRegex,
// issuerLayer: WEBPACK_LAYERS.server,
// use: {
// loader: 'next-flight-client-loader',
// },
// },
// _app should be treated as a client component as well as all its dependencies.
{
test: new RegExp(`_app\\.(${rawPageExtensions.join('|')})$`),
layer: WEBPACK_LAYERS.client,
},
] ]
: [] : []
: []), : []),
...@@ -1841,11 +1821,10 @@ export default async function getBaseWebpackConfig( ...@@ -1841,11 +1821,10 @@ export default async function getBaseWebpackConfig(
isClient && isClient &&
new AppBuildManifestPlugin({ dev }), new AppBuildManifestPlugin({ dev }),
hasServerComponents && hasServerComponents &&
!!config.experimental.appDir &&
(isClient (isClient
? new FlightManifestPlugin({ ? new FlightManifestPlugin({
dev, dev,
appDir: !!config.experimental.appDir,
pageExtensions: rawPageExtensions,
}) })
: new FlightClientEntryPlugin({ : new FlightClientEntryPlugin({
dev, dev,
...@@ -1995,7 +1974,7 @@ export default async function getBaseWebpackConfig( ...@@ -1995,7 +1974,7 @@ export default async function getBaseWebpackConfig(
const configVars = JSON.stringify({ const configVars = JSON.stringify({
crossOrigin: config.crossOrigin, crossOrigin: config.crossOrigin,
pageExtensions: rawPageExtensions, pageExtensions: pageExtensions,
trailingSlash: config.trailingSlash, trailingSlash: config.trailingSlash,
buildActivity: config.devIndicators.buildActivity, buildActivity: config.devIndicators.buildActivity,
buildActivityPosition: config.devIndicators.buildActivityPosition, buildActivityPosition: config.devIndicators.buildActivityPosition,
......
...@@ -501,7 +501,7 @@ export const css = curry(async function css( ...@@ -501,7 +501,7 @@ export const css = curry(async function css(
// If it's inside the app dir, but not importing from a layout file, // If it's inside the app dir, but not importing from a layout file,
// throw an error. // throw an error.
and: [ctx.rootDirectory], and: [ctx.rootDirectory],
not: [/layout(\.client|\.server)?\.(js|mjs|jsx|ts|tsx)$/], not: [/layout\.(js|mjs|jsx|ts|tsx)$/],
} }
: undefined, : undefined,
use: { use: {
......
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info' import type {
MiddlewareMatcher,
RSCModuleType,
} from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
/** /**
...@@ -17,9 +20,15 @@ export function getModuleBuildInfo(webpackModule: webpack.Module) { ...@@ -17,9 +20,15 @@ export function getModuleBuildInfo(webpackModule: webpack.Module) {
route?: RouteMeta route?: RouteMeta
importLocByPath?: Map<string, any> importLocByPath?: Map<string, any>
rootDir?: string rootDir?: string
rsc?: RSCMeta
} }
} }
export interface RSCMeta {
type?: RSCModuleType
requests?: string[] // client requests in flight client entry
}
export interface RouteMeta { export interface RouteMeta {
page: string page: string
absolutePagePath: string absolutePagePath: string
......
...@@ -3,7 +3,6 @@ import { stringifyRequest } from '../stringify-request' ...@@ -3,7 +3,6 @@ import { stringifyRequest } from '../stringify-request'
export type ClientPagesLoaderOptions = { export type ClientPagesLoaderOptions = {
absolutePagePath: string absolutePagePath: string
page: string page: string
isServerComponent?: boolean
} }
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters // this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
...@@ -13,14 +12,12 @@ function nextClientPagesLoader(this: any) { ...@@ -13,14 +12,12 @@ function nextClientPagesLoader(this: any) {
) )
return pagesLoaderSpan.traceFn(() => { return pagesLoaderSpan.traceFn(() => {
const { absolutePagePath, page, isServerComponent } = const { absolutePagePath, page } =
this.getOptions() as ClientPagesLoaderOptions this.getOptions() as ClientPagesLoaderOptions
pagesLoaderSpan.setAttribute('absolutePagePath', absolutePagePath) pagesLoaderSpan.setAttribute('absolutePagePath', absolutePagePath)
const stringifiedPageRequest = isServerComponent const stringifiedPageRequest = stringifyRequest(this, absolutePagePath)
? JSON.stringify(absolutePagePath + '!')
: stringifyRequest(this, absolutePagePath)
const stringifiedPage = JSON.stringify(page) const stringifiedPage = JSON.stringify(page)
return ` return `
......
...@@ -118,7 +118,7 @@ export default async function edgeSSRLoader(this: any) { ...@@ -118,7 +118,7 @@ export default async function edgeSSRLoader(this: any) {
config: ${stringifiedConfig}, config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)}, buildId: ${JSON.stringify(buildId)},
}) })
export const ComponentMod = pageMod export const ComponentMod = pageMod
export default function(opts) { export default function(opts) {
......
import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
import { getModuleBuildInfo } from './get-module-build-info'
export type ClientComponentImports = string[] export type ClientComponentImports = string[]
export type CssImports = Record<string, string[]> export type CssImports = Record<string, string[]>
...@@ -37,5 +40,11 @@ export default async function transformSource(this: any): Promise<string> { ...@@ -37,5 +40,11 @@ export default async function transformSource(this: any): Promise<string> {
export default function RSC() {}; export default function RSC() {};
` `
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.rsc = {
type: RSC_MODULE_TYPES.client,
requests,
}
return code return code
} }
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path'
import { checkExports } from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc'
function containsPath(parent: string, child: string) {
const relation = path.relative(parent, child)
return !!relation && !relation.startsWith('..') && !path.isAbsolute(relation)
}
export default async function transformSource(
this: any,
source: string,
map: any
) {
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const callback = this.async()
const appDir = path.join(this.rootContext, 'app')
const isUnderAppDir = containsPath(appDir, this.resourcePath)
const filename = path.basename(this.resourcePath)
const isPageOrLayoutFile = /^(page|layout)\.client\.\w+$/.test(filename)
const createError = (name: string) =>
new Error(
`${name} is not supported in client components.\nFrom: ${this.resourcePath}`
)
if (isUnderAppDir && isPageOrLayoutFile) {
const swcAST = await parse(source, {
filename: this.resourcePath,
isModule: 'unknown',
})
const { ssg, ssr } = checkExports(swcAST)
if (ssg) {
this.emitError(createError('getStaticProps'))
}
if (ssr) {
this.emitError(createError('getServerSideProps'))
}
}
const output = `
const { createProxy } = require("private-next-rsc-mod-ref-proxy")\n
module.exports = createProxy(${JSON.stringify(this.resourcePath)})
`
// Pass empty sourcemap
callback(null, output, map)
return
}
import path from 'path'
import { RSC_MODULE_TYPES } from '../../../../shared/lib/constants'
import {
checkExports,
getRSCModuleType,
} from '../../../analysis/get-page-static-info'
import { parse } from '../../../swc'
import { getModuleBuildInfo } from '../get-module-build-info'
function transformServer(source: string, isESModule: boolean) {
return (
source +
(isESModule ? `export const __next_rsc__` : `exports.__next_rsc__`) +
` = { __webpack_require__, server: true }\n`
)
}
function containsPath(parent: string, child: string) {
const relation = path.relative(parent, child)
return !!relation && !relation.startsWith('..') && !path.isAbsolute(relation)
}
const isPageOrLayoutFile = (filePath: string) => {
const filename = path.basename(filePath)
return /[\\/]?(page|layout)\.(js|ts)x?$/.test(filename)
}
export default async function transformSource(
this: any,
source: string,
sourceMap: any
) {
// Avoid buffer to be consumed
if (typeof source !== 'string') {
throw new Error('Expected source to have been transformed to a string.')
}
const { resourcePath } = this
const callback = this.async()
const buildInfo = getModuleBuildInfo(this._module)
const swcAST = await parse(source, {
filename: resourcePath,
isModule: 'unknown',
})
const rscType = getRSCModuleType(source)
const isModule = swcAST.type === 'Module'
const createError = (name: string) =>
new Error(
`${name} is not supported in client components.\nFrom: ${this.resourcePath}`
)
const appDir = path.join(this.rootContext, 'app')
const isUnderAppDir = containsPath(appDir, this.resourcePath)
const isResourcePageOrLayoutFile = isPageOrLayoutFile(this.resourcePath)
// If client entry has any gSSP/gSP data fetching methods, error
function errorForInvalidDataFetching(onError: (error: any) => void) {
if (isUnderAppDir && isResourcePageOrLayoutFile) {
const { ssg, ssr } = checkExports(swcAST)
if (ssg) {
onError(createError('getStaticProps'))
}
if (ssr) {
onError(createError('getServerSideProps'))
}
}
}
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
buildInfo.rsc = { type: rscType }
if (buildInfo.rsc?.type === RSC_MODULE_TYPES.client) {
errorForInvalidDataFetching(this.emitError)
return callback(null, source, sourceMap)
}
const code = transformServer(source, isModule)
return callback(null, code, sourceMap)
}
import { parse } from '../../swc'
export default async function transformSource(
this: any,
source: string
): Promise<string> {
const { resourcePath } = this
const ast = await parse(source, {
filename: resourcePath,
isModule: 'unknown',
})
const isModule = ast.type === 'Module'
return (
source +
(isModule
? `
export const __next_rsc__ = {
__webpack_require__,
server: true
}
`
: `
exports.__next_rsc__ = {
__webpack_require__,
server: true
}
`)
)
}
import { getPageStaticInfo } from '../../analysis/get-page-static-info' import { RSC_MODULE_TYPES } from '../../../shared/lib/constants'
export const defaultJsFileExtensions = ['js', 'mjs', 'jsx', 'ts', 'tsx']
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif']
const nextClientComponents = [ const nextClientComponents = [
'dist/client/link', 'dist/client/link',
'dist/client/image', 'dist/client/image',
...@@ -11,46 +9,26 @@ const nextClientComponents = [ ...@@ -11,46 +9,26 @@ const nextClientComponents = [
'dist/shared/lib/dynamic', 'dist/shared/lib/dynamic',
] ]
export function buildExports(moduleExports: any, isESM: boolean) { const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'avif']
let ret = '' const imageRegex = new RegExp(`\\.(${imageExtensions.join('|')})$`)
Object.keys(moduleExports).forEach((key) => {
const exportExpression = isESM
? `export ${key === 'default' ? key : `const ${key} =`} ${
moduleExports[key]
}`
: `exports.${key} = ${moduleExports[key]}`
ret += exportExpression + '\n'
})
return ret
}
// Special cases for Next.js APIs that are considered as client components: const NEXT_API_CLIENT_RSC_REGEX = new RegExp(
// - .client.[ext] `next[\\\\/](${nextClientComponents.join('|')})(\\.js)?`
// - next built-in client components
// - .[imageExt]
export const clientComponentRegex = new RegExp(
'(' +
`\\.client(\\.(${defaultJsFileExtensions.join('|')}))?|` +
`next[\\\\/](${nextClientComponents.join('|')})(\\.js)?|` +
`\\.(${imageExtensions.join('|')})` +
')$'
) )
export const serverComponentRegex = new RegExp( // Cover resource paths like `next/dist/client/*`
`\\.server(\\.(${defaultJsFileExtensions.join('|')}))?$` export function isNextBuiltInClientComponent(resource: string) {
) return NEXT_API_CLIENT_RSC_REGEX.test(resource)
}
export async function loadEdgeFunctionConfigFromFile( export function isClientComponentModule(mod: {
absolutePagePath: string, resource: string
resolve: (context: string, request: string) => Promise<string> buildInfo: any
) { }) {
const pageFilePath = await resolve('/', absolutePagePath) const hasClientDirective = mod.buildInfo.rsc?.type === RSC_MODULE_TYPES.client
return ( return (
await getPageStaticInfo({ isNextBuiltInClientComponent(mod.resource) ||
nextConfig: {}, hasClientDirective ||
pageFilePath, imageRegex.test(mod.resource)
isDev: false, )
})
).middleware
} }
import { stringify } from 'querystring' import { stringify } from 'querystring'
import path from 'path' import path from 'path'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { clientComponentRegex } from '../loaders/utils'
import { import {
getInvalidator, getInvalidator,
entries, entries,
...@@ -18,6 +17,7 @@ import { ...@@ -18,6 +17,7 @@ import {
FLIGHT_SERVER_CSS_MANIFEST, FLIGHT_SERVER_CSS_MANIFEST,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { FlightCSSManifest } from './flight-manifest-plugin' import { FlightCSSManifest } from './flight-manifest-plugin'
import { isClientComponentModule } from '../loaders/utils'
interface Options { interface Options {
dev: boolean dev: boolean
...@@ -131,10 +131,7 @@ export class FlightClientEntryPlugin { ...@@ -131,10 +131,7 @@ export class FlightClientEntryPlugin {
: layoutOrPageRequest : layoutOrPageRequest
// Replace file suffix as `.js` will be added. // Replace file suffix as `.js` will be added.
const bundlePath = relativeRequest.replace( const bundlePath = relativeRequest.replace(/\.(js|ts)x?$/, '')
/(\.server|\.client)?\.(js|ts)x?$/,
''
)
promises.push( promises.push(
this.injectClientEntryAndSSRModules({ this.injectClientEntryAndSSRModules({
...@@ -240,7 +237,7 @@ export class FlightClientEntryPlugin { ...@@ -240,7 +237,7 @@ export class FlightClientEntryPlugin {
visitedBySegment[layoutOrPageRequest].add(modRequest) visitedBySegment[layoutOrPageRequest].add(modRequest)
const isCSS = regexCSS.test(modRequest) const isCSS = regexCSS.test(modRequest)
const isClientComponent = clientComponentRegex.test(modRequest) const isClientComponent = isClientComponentModule(mod)
if (isCSS) { if (isCSS) {
serverCSSImports[layoutOrPageRequest] = serverCSSImports[layoutOrPageRequest] =
......
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { FLIGHT_MANIFEST } from '../../../shared/lib/constants' import { FLIGHT_MANIFEST } from '../../../shared/lib/constants'
import { clientComponentRegex } from '../loaders/utils'
import { relative } from 'path' import { relative } from 'path'
import { isClientComponentModule } from '../loaders/utils'
// This is the module that will be used to anchor all client references to. // This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on. // I.e. it will have all the client files as async deps from this point on.
...@@ -19,8 +19,6 @@ import { relative } from 'path' ...@@ -19,8 +19,6 @@ import { relative } from 'path'
interface Options { interface Options {
dev: boolean dev: boolean
appDir: boolean
pageExtensions: string[]
} }
/** /**
...@@ -64,13 +62,9 @@ const PLUGIN_NAME = 'FlightManifestPlugin' ...@@ -64,13 +62,9 @@ const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin { export class FlightManifestPlugin {
dev: Options['dev'] = false dev: Options['dev'] = false
pageExtensions: Options['pageExtensions']
appDir: Options['appDir'] = false
constructor(options: Options) { constructor(options: Options) {
this.dev = options.dev this.dev = options.dev
this.appDir = options.appDir
this.pageExtensions = options.pageExtensions
} }
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
...@@ -109,9 +103,36 @@ export class FlightManifestPlugin { ...@@ -109,9 +103,36 @@ export class FlightManifestPlugin {
const manifest: FlightManifest = { const manifest: FlightManifest = {
__ssr_module_mapping__: {}, __ssr_module_mapping__: {},
} }
const appDir = this.appDir
const dev = this.dev const dev = this.dev
const clientRequestsSet = new Set()
// Collect client requests
function collectClientRequest(mod: webpack.NormalModule) {
if (mod.resource === '' && mod.buildInfo.rsc) {
const { requests = [] } = mod.buildInfo.rsc
requests.forEach((r: string) => {
clientRequestsSet.add(require.resolve(r))
})
}
}
compilation.chunkGroups.forEach((chunkGroup) => {
chunkGroup.chunks.forEach((chunk: webpack.Chunk) => {
const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
chunk
// TODO: Update type so that it doesn't have to be cast.
) as Iterable<webpack.NormalModule>
for (const mod of chunkModules) {
collectClientRequest(mod)
const anyModule = mod as any
if (anyModule.modules) {
for (const subMod of anyModule.modules) collectClientRequest(subMod)
}
}
})
})
compilation.chunkGroups.forEach((chunkGroup) => { compilation.chunkGroups.forEach((chunkGroup) => {
const cssResourcesInChunkGroup = new Set<string>() const cssResourcesInChunkGroup = new Set<string>()
let entryFilepath: string = '' let entryFilepath: string = ''
...@@ -122,8 +143,9 @@ export class FlightManifestPlugin { ...@@ -122,8 +143,9 @@ export class FlightManifestPlugin {
mod: webpack.NormalModule mod: webpack.NormalModule
) { ) {
const isCSSModule = const isCSSModule =
mod.resource?.endsWith('.css') ||
mod.type === 'css/mini-extract' || mod.type === 'css/mini-extract' ||
(mod.loaders && (!!mod.loaders &&
(dev (dev
? mod.loaders.some((item) => ? mod.loaders.some((item) =>
item.loader.includes('next-style-loader/index.js') item.loader.includes('next-style-loader/index.js')
...@@ -138,7 +160,9 @@ export class FlightManifestPlugin { ...@@ -138,7 +160,9 @@ export class FlightManifestPlugin {
mod._identifier.slice(mod._identifier.lastIndexOf('!') + 1) mod._identifier.slice(mod._identifier.lastIndexOf('!') + 1)
: mod.resource : mod.resource
if (!resource) return if (!resource) {
return
}
const moduleExports = manifest[resource] || {} const moduleExports = manifest[resource] || {}
const moduleIdMapping = manifest.__ssr_module_mapping__ const moduleIdMapping = manifest.__ssr_module_mapping__
...@@ -173,14 +197,13 @@ export class FlightManifestPlugin { ...@@ -173,14 +197,13 @@ export class FlightManifestPlugin {
return return
} }
// TODO: Hook into deps instead of the target module. // Only apply following logic to client module requests from client entry,
// That way we know by the type of dep whether to include. // or if the module is marked as client module.
// It also resolves conflicts when the same module is in multiple chunks. if (!clientRequestsSet.has(resource) && !isClientComponentModule(mod)) {
if (!clientComponentRegex.test(resource)) {
return return
} }
if (/\/(page|layout)\.client\.(ts|js)x?$/.test(resource)) { if (/[\\/](page|layout)\.(ts|js)x?$/.test(resource)) {
entryFilepath = resource entryFilepath = resource
} }
...@@ -207,6 +230,17 @@ export class FlightManifestPlugin { ...@@ -207,6 +230,17 @@ export class FlightManifestPlugin {
]), ]),
] ]
function getAppPathRequiredChunks() {
return chunkGroup.chunks.map((requiredChunk: webpack.Chunk) => {
return (
requiredChunk.id +
':' +
(requiredChunk.name || requiredChunk.id) +
(dev ? '' : '-' + requiredChunk.hash)
)
})
}
const moduleExportedKeys = ['', '*'] const moduleExportedKeys = ['', '*']
.concat( .concat(
[...exportsInfo.exports] [...exportsInfo.exports]
...@@ -217,29 +251,10 @@ export class FlightManifestPlugin { ...@@ -217,29 +251,10 @@ export class FlightManifestPlugin {
.filter((name) => name !== null) .filter((name) => name !== null)
moduleExportedKeys.forEach((name) => { moduleExportedKeys.forEach((name) => {
let requiredChunks: ManifestChunks = [] // If the chunk is from `app/` chunkGroup, use it first.
if (!moduleExports[name]) { // This make sure not to load the overlapped chunk from `pages/` chunkGroup
const isRelatedChunk = (c: webpack.Chunk) => { if (!moduleExports[name] || chunkGroup.name?.startsWith('app/')) {
// If current chunk is a page, it should require the related page chunk; const requiredChunks = getAppPathRequiredChunks()
// If current chunk is a component, it should filter out the related page chunk;
return (
chunk.name?.startsWith('pages/') ||
!c.name?.startsWith('pages/')
)
}
if (appDir) {
requiredChunks = chunkGroup.chunks
.filter(isRelatedChunk)
.map((requiredChunk: webpack.Chunk) => {
return (
requiredChunk.id +
':' +
(requiredChunk.name || requiredChunk.id) +
(dev ? '' : '-' + requiredChunk.hash)
)
})
}
moduleExports[name] = { moduleExports[name] = {
id, id,
...@@ -249,11 +264,9 @@ export class FlightManifestPlugin { ...@@ -249,11 +264,9 @@ export class FlightManifestPlugin {
} }
moduleIdMapping[id] = moduleIdMapping[id] || {} moduleIdMapping[id] = moduleIdMapping[id] || {}
if (!moduleIdMapping[id][name]) { moduleIdMapping[id][name] = {
moduleIdMapping[id][name] = { ...moduleExports[name],
...moduleExports[name], id: ssrNamedModuleId,
id: ssrNamedModuleId,
}
} }
}) })
......
...@@ -25,7 +25,7 @@ import { ...@@ -25,7 +25,7 @@ import {
FlightCSSManifest, FlightCSSManifest,
FlightManifest, FlightManifest,
} from '../build/webpack/plugins/flight-manifest-plugin' } from '../build/webpack/plugins/flight-manifest-plugin'
import { FlushEffectsContext } from '../client/components/hooks-client' import { FlushEffectsContext } from '../shared/lib/flush-effects'
import { stripInternalQueries } from './internal-utils' import { stripInternalQueries } from './internal-utils'
import type { ComponentsType } from '../build/webpack/loaders/next-app-loader' import type { ComponentsType } from '../build/webpack/loaders/next-app-loader'
......
...@@ -20,7 +20,11 @@ import * as Log from '../../build/output/log' ...@@ -20,7 +20,11 @@ import * as Log from '../../build/output/log'
import getBaseWebpackConfig from '../../build/webpack-config' import getBaseWebpackConfig from '../../build/webpack-config'
import { APP_DIR_ALIAS } from '../../lib/constants' import { APP_DIR_ALIAS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
import { BLOCKED_PAGES, COMPILER_NAMES } from '../../shared/lib/constants' import {
BLOCKED_PAGES,
COMPILER_NAMES,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
import { __ApiPreviewProps } from '../api-utils' import { __ApiPreviewProps } from '../api-utils'
import { getPathMatch } from '../../shared/lib/router/utils/path-match' import { getPathMatch } from '../../shared/lib/router/utils/path-match'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
...@@ -35,18 +39,13 @@ import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page ...@@ -35,18 +39,13 @@ import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { fileExists } from '../../lib/file-exists' import { fileExists } from '../../lib/file-exists'
import { import { difference, isMiddlewareFilename } from '../../build/utils'
difference,
withoutRSCExtensions,
isMiddlewareFilename,
} from '../../build/utils'
import { DecodeError } from '../../shared/lib/utils' import { DecodeError } from '../../shared/lib/utils'
import { Span, trace } from '../../trace' import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error' import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws' import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info' import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { serverComponentRegex } from '../../build/webpack/loaders/utils'
import { UnwrapPromise } from '../../lib/coalesced-function' import { UnwrapPromise } from '../../lib/coalesced-function'
function diff(a: Set<any>, b: Set<any>) { function diff(a: Set<any>, b: Set<any>) {
...@@ -404,9 +403,7 @@ export default class HotReloader { ...@@ -404,9 +403,7 @@ export default class HotReloader {
private async getWebpackConfig(span: Span) { private async getWebpackConfig(span: Span) {
const webpackConfigSpan = span.traceChild('get-webpack-config') const webpackConfigSpan = span.traceChild('get-webpack-config')
const rawPageExtensions = this.hasServerComponents const pageExtensions = this.config.pageExtensions
? withoutRSCExtensions(this.config.pageExtensions)
: this.config.pageExtensions
return webpackConfigSpan.traceAsyncFn(async () => { return webpackConfigSpan.traceAsyncFn(async () => {
const pagePaths = !this.pagesDir const pagePaths = !this.pagesDir
...@@ -415,11 +412,11 @@ export default class HotReloader { ...@@ -415,11 +412,11 @@ export default class HotReloader {
.traceChild('get-page-paths') .traceChild('get-page-paths')
.traceAsyncFn(() => .traceAsyncFn(() =>
Promise.all([ Promise.all([
findPageFile(this.pagesDir!, '/_app', rawPageExtensions, false), findPageFile(this.pagesDir!, '/_app', pageExtensions, false),
findPageFile( findPageFile(
this.pagesDir!, this.pagesDir!,
'/_document', '/_document',
rawPageExtensions, pageExtensions,
false false
), ),
]) ])
...@@ -429,7 +426,6 @@ export default class HotReloader { ...@@ -429,7 +426,6 @@ export default class HotReloader {
.traceChild('create-pages-mapping') .traceChild('create-pages-mapping')
.traceFn(() => .traceFn(() =>
createPagesMapping({ createPagesMapping({
hasServerComponents: this.hasServerComponents,
isDev: true, isDev: true,
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
pagesType: 'pages', pagesType: 'pages',
...@@ -444,6 +440,7 @@ export default class HotReloader { ...@@ -444,6 +440,7 @@ export default class HotReloader {
.traceChild('create-entrypoints') .traceChild('create-entrypoints')
.traceAsyncFn(() => .traceAsyncFn(() =>
createEntrypoints({ createEntrypoints({
appDir: this.appDir,
buildId: this.buildId, buildId: this.buildId,
config: this.config, config: this.config,
envFiles: [], envFiles: [],
...@@ -511,6 +508,7 @@ export default class HotReloader { ...@@ -511,6 +508,7 @@ export default class HotReloader {
isDevFallback: true, isDevFallback: true,
entrypoints: ( entrypoints: (
await createEntrypoints({ await createEntrypoints({
appDir: this.appDir,
buildId: this.buildId, buildId: this.buildId,
config: this.config, config: this.config,
envFiles: [], envFiles: [],
...@@ -598,10 +596,7 @@ export default class HotReloader { ...@@ -598,10 +596,7 @@ export default class HotReloader {
} }
} }
const isServerComponent = isEntry const isAppPath = !!this.appDir && bundlePath.startsWith('app/')
? serverComponentRegex.test(entryData.absolutePagePath)
: false
const staticInfo = isEntry const staticInfo = isEntry
? await getPageStaticInfo({ ? await getPageStaticInfo({
pageFilePath: entryData.absolutePagePath, pageFilePath: entryData.absolutePagePath,
...@@ -609,6 +604,8 @@ export default class HotReloader { ...@@ -609,6 +604,8 @@ export default class HotReloader {
isDev: true, isDev: true,
}) })
: {} : {}
const isServerComponent =
isAppPath && staticInfo.rsc !== RSC_MODULE_TYPES.client
await runDependingOnPageType({ await runDependingOnPageType({
page, page,
...@@ -616,9 +613,8 @@ export default class HotReloader { ...@@ -616,9 +613,8 @@ export default class HotReloader {
onEdgeServer: () => { onEdgeServer: () => {
// TODO-APP: verify if child entry should support. // TODO-APP: verify if child entry should support.
if (!isEdgeServerCompilation || !isEntry) return if (!isEdgeServerCompilation || !isEntry) return
const isApp = this.appDir && bundlePath.startsWith('app/')
const appDirLoader = const appDirLoader =
isApp && this.appDir isAppPath && this.appDir
? getAppEntry({ ? getAppEntry({
name: bundlePath, name: bundlePath,
appPaths: entryData.appPaths, appPaths: entryData.appPaths,
...@@ -649,7 +645,7 @@ export default class HotReloader { ...@@ -649,7 +645,7 @@ export default class HotReloader {
pages: this.pagesMapping, pages: this.pagesMapping,
isServerComponent, isServerComponent,
appDirLoader, appDirLoader,
pagesType: isApp ? 'app' : undefined, pagesType: isAppPath ? 'app' : undefined,
}), }),
appDir: this.config.experimental.appDir, appDir: this.config.experimental.appDir,
}) })
......
...@@ -12,7 +12,6 @@ import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-sl ...@@ -12,7 +12,6 @@ import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-sl
import { removePagePathTail } from '../../shared/lib/page-path/remove-page-path-tail' import { removePagePathTail } from '../../shared/lib/page-path/remove-page-path-tail'
import { reportTrigger } from '../../build/output' import { reportTrigger } from '../../build/output'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { serverComponentRegex } from '../../build/webpack/loaders/utils'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info' import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { isMiddlewareFile, isMiddlewareFilename } from '../../build/utils' import { isMiddlewareFile, isMiddlewareFilename } from '../../build/utils'
import { PageNotFoundError } from '../../shared/lib/utils' import { PageNotFoundError } from '../../shared/lib/utils'
...@@ -21,6 +20,7 @@ import { ...@@ -21,6 +20,7 @@ import {
CompilerNameValues, CompilerNameValues,
COMPILER_INDEXES, COMPILER_INDEXES,
COMPILER_NAMES, COMPILER_NAMES,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
const debug = origDebug('next:on-demand-entry-handler') const debug = origDebug('next:on-demand-entry-handler')
...@@ -578,11 +578,8 @@ export function onDemandEntryHandler({ ...@@ -578,11 +578,8 @@ export function onDemandEntryHandler({
appDir appDir
) )
const isServerComponent = serverComponentRegex.test(
pagePathData.absolutePagePath
)
const isInsideAppDir = const isInsideAppDir =
appDir && pagePathData.absolutePagePath.startsWith(appDir) !!appDir && pagePathData.absolutePagePath.startsWith(appDir)
const addEntry = ( const addEntry = (
compilerType: CompilerNameValues compilerType: CompilerNameValues
...@@ -636,6 +633,8 @@ export function onDemandEntryHandler({ ...@@ -636,6 +633,8 @@ export function onDemandEntryHandler({
}) })
const added = new Map<CompilerNameValues, ReturnType<typeof addEntry>>() const added = new Map<CompilerNameValues, ReturnType<typeof addEntry>>()
const isServerComponent =
isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client
await runDependingOnPageType({ await runDependingOnPageType({
page: pagePathData.page, page: pagePathData.page,
......
...@@ -96,6 +96,11 @@ export const DEFAULT_SANS_SERIF_FONT = 'Arial' ...@@ -96,6 +96,11 @@ export const DEFAULT_SANS_SERIF_FONT = 'Arial'
export const STATIC_STATUS_PAGES = ['/500'] export const STATIC_STATUS_PAGES = ['/500']
export const TRACE_OUTPUT_VERSION = 1 export const TRACE_OUTPUT_VERSION = 1
export const RSC_MODULE_TYPES = {
client: 'client',
server: 'server',
} as const
// comparing // comparing
// https://nextjs.org/docs/api-reference/edge-runtime // https://nextjs.org/docs/api-reference/edge-runtime
// with // with
......
...@@ -114,7 +114,7 @@ module.exports = function (task) { ...@@ -114,7 +114,7 @@ module.exports = function (task) {
// Make sure the output content keeps the `"client"` directive. // Make sure the output content keeps the `"client"` directive.
// TODO: Remove this once SWC fixes the issue. // TODO: Remove this once SWC fixes the issue.
if (source.startsWith("'client'")) { if (/^['"]client['"]/.test(source)) {
output.code = '"client";\n' + output.code output.code = '"client";\n' + output.code
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import dynamic from 'next/dist/client/components/shared/dynamic' import dynamic from 'next/dist/client/components/shared/dynamic'
const Dynamic = dynamic(() => import('../text-dynamic.client')) const Dynamic = dynamic(() => import('../text-dynamic-client'))
export function NextDynamicClientComponent() { export function NextDynamicClientComponent() {
return <Dynamic /> return <Dynamic />
......
import dynamic from 'next/dist/client/components/shared/dynamic' import dynamic from 'next/dist/client/components/shared/dynamic'
const Dynamic = dynamic(() => import('../text-dynamic.server')) const Dynamic = dynamic(() => import('../text-dynamic-server'))
export function NextDynamicServerComponent() { export function NextDynamicServerComponent() {
return <Dynamic /> return <Dynamic />
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import { useState, lazy } from 'react' import { useState, lazy } from 'react'
const Lazy = lazy(() => import('../text-lazy.client.js')) const Lazy = lazy(() => import('../text-lazy-client.js'))
export function LazyClientComponent() { export function LazyClientComponent() {
let [state] = useState('client') let [state] = useState('client')
......
import { LazyClientComponent } from './dynamic-imports/react-lazy.client' import { LazyClientComponent } from './dynamic-imports/react-lazy-client'
import { NextDynamicServerComponent } from './dynamic-imports/dynamic.server' import { NextDynamicServerComponent } from './dynamic-imports/dynamic-server'
import { NextDynamicClientComponent } from './dynamic-imports/dynamic.client' import { NextDynamicClientComponent } from './dynamic-imports/dynamic-client'
export default function DashboardIndexPage() { export default function DashboardIndexPage() {
return ( return (
......
import ClientComp from './client-comp.client' import ClientComp from './client-comp-client'
export default function DashboardPage(props) { export default function DashboardPage(props) {
return ( return (
<> <>
......
This diff is collapsed.
This diff is collapsed.
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