Skip to content

Commit

Permalink
Refactor client entry plugin to separate methods. (#39162)
Browse files Browse the repository at this point in the history
WIP.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] 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`
- [ ] 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`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)


Co-authored-by: Shu Ding <3676859+shuding@users.noreply.github.com>
  • Loading branch information
timneutkens and shuding committed Aug 12, 2022
1 parent 0c7217b commit b5aa571
Show file tree
Hide file tree
Showing 35 changed files with 863 additions and 507 deletions.
74 changes: 49 additions & 25 deletions packages/next/build/entries.ts
Expand Up @@ -15,12 +15,16 @@ import {
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CompilerNameValues,
COMPILER_NAMES,
EDGE_RUNTIME_WEBPACK,
} from '../shared/lib/constants'
import { __ApiPreviewProps } from '../server/api-utils'
Expand Down Expand Up @@ -203,7 +207,7 @@ export function getEdgeServerEntry(opts: {

return {
import: `next-edge-ssr-loader?${stringify(loaderParams)}!`,
layer: opts.isServerComponent ? 'sc_server' : undefined,
layer: opts.isServerComponent ? WEBPACK_LAYERS.server : undefined,
}
}

Expand All @@ -215,7 +219,7 @@ export function getAppEntry(opts: {
}) {
return {
import: `next-app-loader?${stringify(opts)}!`,
layer: 'sc_server',
layer: WEBPACK_LAYERS.server,
}
}

Expand Down Expand Up @@ -359,7 +363,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}
}

runDependingOnPageType({
await runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
onClient: () => {
Expand Down Expand Up @@ -393,7 +397,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
server[serverBundlePath] = isServerComponent
? {
import: mappings[page],
layer: 'sc_server',
layer: WEBPACK_LAYERS.server,
}
: [mappings[page]]
}
Expand Down Expand Up @@ -435,33 +439,46 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}
}

export function runDependingOnPageType<T>(params: {
export async function runDependingOnPageType<T>(params: {
onClient: () => T
onEdgeServer: () => T
onServer: () => T
page: string
pageRuntime: ServerRuntime
}) {
}): Promise<void> {
if (isMiddlewareFile(params.page)) {
return { edgeServer: params.onEdgeServer() }
} else if (params.page.match(API_ROUTE)) {
return params.pageRuntime === SERVER_RUNTIME.edge
? { edgeServer: params.onEdgeServer() }
: { server: params.onServer() }
} else if (params.page === '/_document') {
return { server: params.onServer() }
} else if (
await params.onEdgeServer()
return
}
if (params.page.match(API_ROUTE)) {
if (params.pageRuntime === SERVER_RUNTIME.edge) {
await params.onEdgeServer()
return
}

await params.onServer()
return
}
if (params.page === '/_document') {
await params.onServer()
return
}
if (
params.page === '/_app' ||
params.page === '/_error' ||
params.page === '/404' ||
params.page === '/500'
) {
return { client: params.onClient(), server: params.onServer() }
} else {
return params.pageRuntime === SERVER_RUNTIME.edge
? { client: params.onClient(), edgeServer: params.onEdgeServer() }
: { client: params.onClient(), server: params.onServer() }
await Promise.all([params.onClient(), params.onServer()])
return
}
if (params.pageRuntime === SERVER_RUNTIME.edge) {
await Promise.all([params.onClient(), params.onEdgeServer()])
return
}

await Promise.all([params.onClient(), params.onServer()])
return
}

export function finalizeEntrypoint({
Expand All @@ -471,7 +488,7 @@ export function finalizeEntrypoint({
isServerComponent,
appDir,
}: {
compilerType?: 'client' | 'server' | 'edge-server'
compilerType?: CompilerNameValues
name: string
value: ObjectValue<webpack5.EntryObject>
isServerComponent?: boolean
Expand All @@ -483,18 +500,25 @@ export function finalizeEntrypoint({
: value

const isApi = name.startsWith('pages/api/')
if (compilerType === 'server') {
if (compilerType === COMPILER_NAMES.server) {
return {
publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
layer: isApi ? 'api' : isServerComponent ? 'sc_server' : undefined,
layer: isApi
? WEBPACK_LAYERS.api
: isServerComponent
? WEBPACK_LAYERS.server
: undefined,
...entry,
}
}

if (compilerType === 'edge-server') {
if (compilerType === COMPILER_NAMES.edgeServer) {
return {
layer: isMiddlewareFilename(name) || isApi ? 'middleware' : undefined,
layer:
isMiddlewareFilename(name) || isApi
? WEBPACK_LAYERS.middleware
: undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false,
Expand All @@ -504,7 +528,7 @@ export function finalizeEntrypoint({

if (
// Client special cases
name !== 'polyfills' &&
name !== CLIENT_STATIC_FILES_RUNTIME_POLYFILLS &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN &&
name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_APP &&
name !== CLIENT_STATIC_FILES_RUNTIME_AMP &&
Expand Down
7 changes: 4 additions & 3 deletions packages/next/build/index.ts
Expand Up @@ -55,6 +55,7 @@ import {
MIDDLEWARE_MANIFEST,
APP_PATHS_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
COMPILER_NAMES,
APP_BUILD_MANIFEST,
} from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
Expand Down Expand Up @@ -749,17 +750,17 @@ export default async function build(
Promise.all([
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'client',
compilerType: COMPILER_NAMES.client,
entrypoints: entrypoints.client,
}),
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'server',
compilerType: COMPILER_NAMES.server,
entrypoints: entrypoints.server,
}),
getBaseWebpackConfig(dir, {
...commonWebpackOptions,
compilerType: 'edge-server',
compilerType: COMPILER_NAMES.edgeServer,
entrypoints: entrypoints.edgeServer,
}),
])
Expand Down
9 changes: 5 additions & 4 deletions packages/next/build/output/index.ts
Expand Up @@ -5,6 +5,7 @@ import createStore from 'next/dist/compiled/unistore'
import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages'
import { OutputState, store as consoleStore } from './store'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import { CompilerNameValues, COMPILER_NAMES } from '../../shared/lib/constants'

export function startedDevelopmentServer(appUrl: string, bindAddr: string) {
consoleStore.setState({ appUrl, bindAddr })
Expand Down Expand Up @@ -238,7 +239,7 @@ export function watchCompilers(
})

function tapCompiler(
key: 'client' | 'server' | 'edgeServer',
key: CompilerNameValues,
compiler: webpack5.Compiler,
onEvent: (status: WebpackStatus) => void
) {
Expand Down Expand Up @@ -268,7 +269,7 @@ export function watchCompilers(
})
}

tapCompiler('client', client, (status) => {
tapCompiler(COMPILER_NAMES.client, client, (status) => {
if (
!status.loading &&
!buildStore.getState().server.loading &&
Expand All @@ -284,7 +285,7 @@ export function watchCompilers(
})
}
})
tapCompiler('server', server, (status) => {
tapCompiler(COMPILER_NAMES.server, server, (status) => {
if (
!status.loading &&
!buildStore.getState().client.loading &&
Expand All @@ -300,7 +301,7 @@ export function watchCompilers(
})
}
})
tapCompiler('edgeServer', edgeServer, (status) => {
tapCompiler(COMPILER_NAMES.edgeServer, edgeServer, (status) => {
if (
!status.loading &&
!buildStore.getState().client.loading &&
Expand Down
41 changes: 22 additions & 19 deletions packages/next/build/webpack-config.ts
Expand Up @@ -13,6 +13,7 @@ import {
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
SERVER_RUNTIME,
WEBPACK_LAYERS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js'
Expand All @@ -28,6 +29,8 @@ import {
SERVERLESS_DIRECTORY,
SERVER_DIRECTORY,
MODERN_BROWSERSLIST_TARGET,
COMPILER_NAMES,
CompilerNameValues,
} from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared'
Expand Down Expand Up @@ -334,13 +337,13 @@ export default async function getBaseWebpackConfig(
reactProductionProfiling = false,
rewrites,
runWebpackSpan,
target = 'server',
target = COMPILER_NAMES.server,
appDir,
middlewareRegex,
}: {
buildId: string
config: NextConfigComplete
compilerType: 'client' | 'server' | 'edge-server'
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack5.EntryObject
hasReactRoot: boolean
Expand All @@ -354,9 +357,9 @@ export default async function getBaseWebpackConfig(
middlewareRegex?: string
}
): Promise<webpack.Configuration> {
const isClient = compilerType === 'client'
const isEdgeServer = compilerType === 'edge-server'
const isNodeServer = compilerType === 'server'
const isClient = compilerType === COMPILER_NAMES.client
const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
const isNodeServer = compilerType === COMPILER_NAMES.server
const { useTypeScript, jsConfig, resolvedBaseUrl } = await loadJsConfig(
dir,
config
Expand Down Expand Up @@ -650,9 +653,9 @@ export default async function getBaseWebpackConfig(
const reactDomDir = dirname(require.resolve('react-dom/package.json'))

const mainFieldsPerCompiler: Record<typeof compilerType, string[]> = {
server: ['main', 'module'],
client: ['browser', 'module', 'main'],
'edge-server': ['browser', 'module', 'main'],
[COMPILER_NAMES.server]: ['main', 'module'],
[COMPILER_NAMES.client]: ['browser', 'module', 'main'],
[COMPILER_NAMES.edgeServer]: ['browser', 'module', 'main'],
}

const resolveConfig = {
Expand Down Expand Up @@ -1310,22 +1313,22 @@ export default async function getBaseWebpackConfig(
// RSC server compilation loaders
{
...serverComponentCodeCondition,
issuerLayer: 'sc_server',
issuerLayer: WEBPACK_LAYERS.server,
use: {
loader: 'next-flight-server-loader',
},
},
{
test: clientComponentRegex,
issuerLayer: 'sc_server',
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: 'sc_client',
layer: WEBPACK_LAYERS.client,
},
]
: []
Expand All @@ -1336,13 +1339,13 @@ export default async function getBaseWebpackConfig(
// same layer.
{
test: rscSharedRegex,
layer: 'rsc_shared_deps',
layer: WEBPACK_LAYERS.rscShared,
},
]
: []),
{
test: /\.(js|cjs|mjs)$/,
issuerLayer: 'api',
issuerLayer: WEBPACK_LAYERS.api,
parser: {
// Switch back to normal URL handling
url: true,
Expand All @@ -1352,7 +1355,7 @@ export default async function getBaseWebpackConfig(
oneOf: [
{
...codeCondition,
issuerLayer: 'api',
issuerLayer: WEBPACK_LAYERS.api,
parser: {
// Switch back to normal URL handling
url: true,
Expand All @@ -1361,7 +1364,7 @@ export default async function getBaseWebpackConfig(
},
{
...codeCondition,
issuerLayer: 'middleware',
issuerLayer: WEBPACK_LAYERS.middleware,
use: getBabelOrSwcLoader(),
},
{
Expand Down Expand Up @@ -1399,7 +1402,7 @@ export default async function getBaseWebpackConfig(
{
oneOf: [
{
issuerLayer: 'middleware',
issuerLayer: WEBPACK_LAYERS.middleware,
resolve: {
fallback: {
process: require.resolve('./polyfills/process'),
Expand Down Expand Up @@ -1499,7 +1502,7 @@ export default async function getBaseWebpackConfig(
[`process.env.${key}`]: JSON.stringify(config.env[key]),
}
}, {}),
...(compilerType !== 'edge-server'
...(compilerType !== COMPILER_NAMES.edgeServer
? {}
: {
EdgeRuntime: JSON.stringify(
Expand Down Expand Up @@ -1785,10 +1788,10 @@ export default async function getBaseWebpackConfig(
dependency: 'url',
loader: 'next-middleware-asset-loader',
type: 'javascript/auto',
layer: 'edge-asset',
layer: WEBPACK_LAYERS.edgeAsset,
})
webpack5Config.module?.rules?.unshift({
issuerLayer: 'edge-asset',
issuerLayer: WEBPACK_LAYERS.edgeAsset,
type: 'asset/source',
})
}
Expand Down

0 comments on commit b5aa571

Please sign in to comment.