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( ...@@ -647,6 +647,8 @@ export async function createEntrypoints(
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
nextConfigExperimentalUseEarlyImport:
config.experimental.useEarlyImport,
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
middlewareConfig: encodeToBase64(staticInfo.middleware || {}), middlewareConfig: encodeToBase64(staticInfo.middleware || {}),
}) })
......
...@@ -47,6 +47,7 @@ export type AppLoaderOptions = { ...@@ -47,6 +47,7 @@ export type AppLoaderOptions = {
isDev?: boolean isDev?: boolean
basePath: string basePath: string
nextConfigOutput?: NextConfig['output'] nextConfigOutput?: NextConfig['output']
nextConfigExperimentalUseEarlyImport?: boolean
middlewareConfig: string middlewareConfig: string
} }
type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions> type AppLoader = webpack.LoaderDefinitionFunction<AppLoaderOptions>
...@@ -170,6 +171,7 @@ async function createTreeCodeFromPath( ...@@ -170,6 +171,7 @@ async function createTreeCodeFromPath(
metadataResolver, metadataResolver,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports,
}: { }: {
page: string page: string
resolveDir: DirResolver resolveDir: DirResolver
...@@ -181,6 +183,7 @@ async function createTreeCodeFromPath( ...@@ -181,6 +183,7 @@ async function createTreeCodeFromPath(
loaderContext: webpack.LoaderContext<AppLoaderOptions> loaderContext: webpack.LoaderContext<AppLoaderOptions>
pageExtensions: PageExtensions pageExtensions: PageExtensions
basePath: string basePath: string
collectedAsyncImports: string[]
} }
): Promise<{ ): Promise<{
treeCode: string treeCode: string
...@@ -233,7 +236,8 @@ async function createTreeCodeFromPath( ...@@ -233,7 +236,8 @@ async function createTreeCodeFromPath(
} }
async function createSubtreePropsFromSegmentPath( async function createSubtreePropsFromSegmentPath(
segments: string[] segments: string[],
nestedCollectedAsyncImports: string[]
): Promise<{ ): Promise<{
treeCode: string treeCode: string
}> { }> {
...@@ -280,7 +284,10 @@ async function createTreeCodeFromPath( ...@@ -280,7 +284,10 @@ async function createTreeCodeFromPath(
}/page` }/page`
const resolvedPagePath = await resolver(matchedPagePath) 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. // 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[ props[
...@@ -291,8 +298,7 @@ async function createTreeCodeFromPath( ...@@ -291,8 +298,7 @@ async function createTreeCodeFromPath(
)}), ${JSON.stringify(resolvedPagePath)}], )}), ${JSON.stringify(resolvedPagePath)}],
${createMetadataExportsCode(metadata)} ${createMetadataExportsCode(metadata)}
}]` }]`
if (resolvedPagePath) continue
continue
} }
// if the parallelSegment was not matched to the __PAGE__ slot, then it's a parallel route at this level. // 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( ...@@ -321,7 +327,10 @@ async function createTreeCodeFromPath(
} }
const { treeCode: pageSubtreeCode } = const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(subSegmentPath) await createSubtreePropsFromSegmentPath(
subSegmentPath,
nestedCollectedAsyncImports
)
const parallelSegmentPath = subSegmentPath.join('/') const parallelSegmentPath = subSegmentPath.join('/')
...@@ -399,6 +408,7 @@ async function createTreeCodeFromPath( ...@@ -399,6 +408,7 @@ async function createTreeCodeFromPath(
const notFoundPath = const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ?? definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath defaultNotFoundPath
nestedCollectedAsyncImports.push(notFoundPath)
subtreeCode = `{ subtreeCode = `{
children: ['${PAGE_SEGMENT_KEY}', {}, { children: ['${PAGE_SEGMENT_KEY}', {}, {
page: [ page: [
...@@ -414,6 +424,7 @@ async function createTreeCodeFromPath( ...@@ -414,6 +424,7 @@ async function createTreeCodeFromPath(
const componentsCode = `{ const componentsCode = `{
${definedFilePaths ${definedFilePaths
.map(([file, filePath]) => { .map(([file, filePath]) => {
if (filePath) nestedCollectedAsyncImports.push(filePath)
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify( return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath filePath
)}), ${JSON.stringify(filePath)}],` )}), ${JSON.stringify(filePath)}],`
...@@ -456,6 +467,7 @@ async function createTreeCodeFromPath( ...@@ -456,6 +467,7 @@ async function createTreeCodeFromPath(
defaultPath = normalizedDefault ?? PARALLEL_ROUTE_DEFAULT_PATH defaultPath = normalizedDefault ?? PARALLEL_ROUTE_DEFAULT_PATH
} }
nestedCollectedAsyncImports.push(defaultPath)
props[normalizeParallelKey(adjacentParallelSegment)] = `[ props[normalizeParallelKey(adjacentParallelSegment)] = `[
'${DEFAULT_SEGMENT_KEY}', '${DEFAULT_SEGMENT_KEY}',
{}, {},
...@@ -476,7 +488,10 @@ async function createTreeCodeFromPath( ...@@ -476,7 +488,10 @@ async function createTreeCodeFromPath(
} }
} }
const { treeCode } = await createSubtreePropsFromSegmentPath([]) const { treeCode } = await createSubtreePropsFromSegmentPath(
[],
collectedAsyncImports
)
return { return {
treeCode: `${treeCode}.children;`, treeCode: `${treeCode}.children;`,
...@@ -510,9 +525,11 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -510,9 +525,11 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
preferredRegion, preferredRegion,
basePath, basePath,
middlewareConfig: middlewareConfigBase64, middlewareConfig: middlewareConfigBase64,
nextConfigExperimentalUseEarlyImport,
} = loaderOptions } = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedAsyncImports: string[] = []
const page = name.replace(/^app/, '') const page = name.replace(/^app/, '')
const middlewareConfig: MiddlewareConfig = JSON.parse( const middlewareConfig: MiddlewareConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
...@@ -690,6 +707,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -690,6 +707,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports,
}) })
if (!treeCodeResult.rootLayout) { if (!treeCodeResult.rootLayout) {
...@@ -738,6 +756,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -738,6 +756,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
loaderContext: this, loaderContext: this,
pageExtensions, pageExtensions,
basePath, basePath,
collectedAsyncImports,
}) })
} }
} }
...@@ -746,7 +765,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -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. // 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. // 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', 'app-page',
{ {
VAR_DEFINITION_PAGE: page, VAR_DEFINITION_PAGE: page,
...@@ -761,6 +780,19 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -761,6 +780,19 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
__next_app_load_chunk__: '() => Promise.resolve()', __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 export default nextAppLoader
...@@ -404,6 +404,11 @@ export interface ExperimentalConfig { ...@@ -404,6 +404,11 @@ export interface ExperimentalConfig {
* @default true * @default true
*/ */
missingSuspenseWithCSRBailout?: boolean missingSuspenseWithCSRBailout?: boolean
/**
* Enables early import feature for app router modules
*/
useEarlyImport?: boolean
} }
export type ExportPathMap = { 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