Unverified Commit f4ac92d3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add flag for early import app router modules (#61168)

Closes NEXT-2236

---------
Co-authored-by: 's avatarEthan Arrowood <ethan@arrowood.dev>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 5be81359
......@@ -647,6 +647,8 @@ export async function createEntrypoints(
basePath: config.basePath,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
nextConfigExperimentalUseEarlyImport:
config.experimental.useEarlyImport,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
})
......
......@@ -47,6 +47,7 @@ export type AppLoaderOptions = {
isDev?: boolean
basePath: string
nextConfigOutput?: NextConfig['output']
nextConfigExperimentalUseEarlyImport?: boolean
middlewareConfig: string
}
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
......@@ -170,6 +171,7 @@ async function createTreeCodeFromPath(
metadataResolver,
pageExtensions,
basePath,
collectedAsyncImports,
}: {
page: string
resolveDir: DirResolver
......@@ -181,6 +183,7 @@ async function createTreeCodeFromPath(
loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions
basePath: string
collectedAsyncImports: string[]
}
): Promise<{
treeCode: string
......@@ -233,7 +236,8 @@ async function createTreeCodeFromPath(
}
async function createSubtreePropsFromSegmentPath(
segments: string[]
segments: string[],
nestedCollectedAsyncImports: string[]
): Promise<{
treeCode: string
}> {
......@@ -280,7 +284,10 @@ async function createTreeCodeFromPath(
}/page`
const resolvedPagePath = await resolver(matchedPagePath)
if (resolvedPagePath) pages.push(resolvedPagePath)
if (resolvedPagePath) {
pages.push(resolvedPagePath)
nestedCollectedAsyncImports.push(resolvedPagePath)
}
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[
......@@ -291,8 +298,7 @@ async function createTreeCodeFromPath(
)}), ${JSON.stringify(resolvedPagePath)}],
${createMetadataExportsCode(metadata)}
}]`
continue
if (resolvedPagePath) continue
}
// if the parallelSegment was not matched to the __PAGE__ slot, then it's a parallel route at this level.
......@@ -321,7 +327,10 @@ async function createTreeCodeFromPath(
}
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(subSegmentPath)
await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedAsyncImports
)
const parallelSegmentPath = subSegmentPath.join('/')
......@@ -399,6 +408,7 @@ async function createTreeCodeFromPath(
const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath
nestedCollectedAsyncImports.push(notFoundPath)
subtreeCode = `{
children: ['${PAGE_SEGMENT_KEY}', {}, {
page: [
......@@ -414,6 +424,7 @@ async function createTreeCodeFromPath(
const componentsCode = `{
${definedFilePaths
.map(([file, filePath]) => {
if (filePath) nestedCollectedAsyncImports.push(filePath)
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
......@@ -456,6 +467,7 @@ async function createTreeCodeFromPath(
defaultPath = normalizedDefault ?? PARALLEL_ROUTE_DEFAULT_PATH
}
nestedCollectedAsyncImports.push(defaultPath)
props[normalizeParallelKey(adjacentParallelSegment)] = `[
'${DEFAULT_SEGMENT_KEY}',
{},
......@@ -476,7 +488,10 @@ async function createTreeCodeFromPath(
}
}
const { treeCode } = await createSubtreePropsFromSegmentPath([])
const { treeCode } = await createSubtreePropsFromSegmentPath(
[],
collectedAsyncImports
)
return {
treeCode: `${treeCode}.children;`,
......@@ -510,9 +525,11 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
preferredRegion,
basePath,
middlewareConfig: middlewareConfigBase64,
nextConfigExperimentalUseEarlyImport,
} = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedAsyncImports: string[] = []
const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString()
......@@ -690,6 +707,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this,
pageExtensions,
basePath,
collectedAsyncImports,
})
if (!treeCodeResult.rootLayout) {
......@@ -738,6 +756,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this,
pageExtensions,
basePath,
collectedAsyncImports,
})
}
}
......@@ -746,7 +765,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
// Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack.
// Any changes to this code should be reflected in Turbopack's app_source.rs and/or app-renderer.tsx as well.
return await loadEntrypoint(
const code = await loadEntrypoint(
'app-page',
{
VAR_DEFINITION_PAGE: page,
......@@ -761,6 +780,19 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
__next_app_load_chunk__: '() => Promise.resolve()',
}
)
// Evaluated the imported modules early in the generated code
const earlyEvaluateCode =
nextConfigExperimentalUseEarlyImport &&
process.env.NODE_ENV === 'production'
? collectedAsyncImports
.map((modulePath) => {
return `import ${JSON.stringify(modulePath)};`
})
.join('\n')
: ''
return earlyEvaluateCode + code
}
export default nextAppLoader
......@@ -404,6 +404,11 @@ export interface ExperimentalConfig {
* @default true
*/
missingSuspenseWithCSRBailout?: boolean
/**
* Enables early import feature for app router modules
*/
useEarlyImport?: boolean
}
export type ExportPathMap = {
......
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