Unverified Commit 142050dd authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix css FOUC in dynamic component (#64294)

### What

CSS imports in components that loaded by `next/dynamic` in client
components will cause the css are missing initial in
SSR, and loaded later on client side which will lead to FOUC. This PR
fixes the issue and get CSS preloaded in the SSR for dynamic components.

### Why

The CSS from client components that created through `next/dynamic` are
not collected in the SSR, unlike RSC rendering we already collect the
CSS resources for each entry so we included them in the server rendering
so the styles are availble at that time. But for client components, we
didn't traverse all the client components and collect the CSS resources.

In pages router we kinda collect all the dynamic imports and preload
them during SSR, but this approach is not able to be applied to app
router due to different architecture. Since we already have all the
dynamic imports info and their related chunks in
react-loadable-manifest, so we can do the similar "preloading" thing in
app router. We use the current dynamic module key (`app/page.js ->
../components/foo.js`) which created by SWC transform and match it in
the react loadable manifest that accessed from `AsyncLocalStorage`, to
get the css files created by webpack then render them as preload
styleshee links. In this way we can SSR all the related CSS resources
for dynamic client components.

The reason we pass down the react loadable manifest through
`AsyncLocalStorage` is that it's sort of exclude the manifest from RSC
payload as it's not required for hydration, but only required for SSR.

Note: this issue only occurred in dynamic rendering case for client
components.

### Other Changes Overview

- Change the react loadable manifest key from pages dir based relative
path to a source dir based relative path, to support cases with both
directory or only one of them

Closes NEXT-2578
Fixes #61212
Fixes #61111
Fixes #62940

Replacement for #64021 but only with production test
parent bccf55c8
...@@ -924,7 +924,7 @@ impl PageEndpoint { ...@@ -924,7 +924,7 @@ impl PageEndpoint {
) -> Result<Vc<OutputAssets>> { ) -> Result<Vc<OutputAssets>> {
let this = self.await?; let this = self.await?;
let node_root = this.pages_project.project().node_root(); let node_root = this.pages_project.project().node_root();
let pages_dir = this.pages_project.pages_dir().await?; let project_src_dir = this.pages_project.pages_dir().parent().await?;
let dynamic_import_entries = &*dynamic_import_entries.await?; let dynamic_import_entries = &*dynamic_import_entries.await?;
...@@ -937,12 +937,12 @@ impl PageEndpoint { ...@@ -937,12 +937,12 @@ impl PageEndpoint {
let chunk_output = chunk_output.await?; let chunk_output = chunk_output.await?;
output.extend(chunk_output.iter().copied()); output.extend(chunk_output.iter().copied());
// https://github.com/vercel/next.js/blob/b7c85b87787283d8fb86f705f67bdfabb6b654bb/packages/next-swc/crates/next-transform-dynamic/src/lib.rs#L230 // https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts
// For the pages dir, next_dynamic transform puts relative paths to the pages // next_dynamic transform puts relative paths to the project dir
// dir for the origin import. // dir for the origin import.
let id = format!( let id = format!(
"{} -> {}", "{} -> {}",
pages_dir project_src_dir
.get_path_to(origin_path) .get_path_to(origin_path)
.map_or_else(|| origin_path.to_string(), |path| path.to_string()), .map_or_else(|| origin_path.to_string(), |path| path.to_string()),
import import
......
...@@ -40,7 +40,7 @@ pub async fn get_next_client_transforms_rules( ...@@ -40,7 +40,7 @@ pub async fn get_next_client_transforms_rules(
let mdx_rs = *next_config.mdx_rs().await?; let mdx_rs = *next_config.mdx_rs().await?;
rules.push(get_next_font_transform_rule(mdx_rs)); rules.push(get_next_font_transform_rule(mdx_rs));
let pages_dir = match context_ty { let pages_or_app_dir = match context_ty {
ClientContextType::Pages { pages_dir } => { ClientContextType::Pages { pages_dir } => {
if !foreign_code { if !foreign_code {
rules.push( rules.push(
...@@ -59,12 +59,12 @@ pub async fn get_next_client_transforms_rules( ...@@ -59,12 +59,12 @@ pub async fn get_next_client_transforms_rules(
} }
Some(pages_dir) Some(pages_dir)
} }
ClientContextType::App { .. } => { ClientContextType::App { app_dir } => {
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Client, ActionsTransform::Client,
mdx_rs, mdx_rs,
)); ));
None Some(app_dir)
} }
ClientContextType::Fallback | ClientContextType::Other => None, ClientContextType::Fallback | ClientContextType::Other => None,
}; };
...@@ -74,7 +74,9 @@ pub async fn get_next_client_transforms_rules( ...@@ -74,7 +74,9 @@ pub async fn get_next_client_transforms_rules(
rules.push(get_next_cjs_optimizer_rule(mdx_rs)); rules.push(get_next_cjs_optimizer_rule(mdx_rs));
rules.push(get_next_pure_rule(mdx_rs)); rules.push(get_next_pure_rule(mdx_rs));
rules.push(get_next_dynamic_transform_rule(false, false, pages_dir, mode, mdx_rs).await?); rules.push(
get_next_dynamic_transform_rule(false, false, pages_or_app_dir, mode, mdx_rs).await?,
);
rules.push(get_next_image_rule()); rules.push(get_next_image_rule());
rules.push(get_next_page_static_info_assert_rule( rules.push(get_next_page_static_info_assert_rule(
......
...@@ -50,7 +50,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -50,7 +50,7 @@ pub async fn get_next_server_transforms_rules(
)); ));
} }
let (is_server_components, pages_dir) = match context_ty { let (is_server_components, pages_or_app_dir) = match context_ty {
ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => { ServerContextType::Pages { pages_dir } | ServerContextType::PagesApi { pages_dir } => {
if !foreign_code { if !foreign_code {
rules.push(get_next_disallow_export_all_in_page_rule( rules.push(get_next_disallow_export_all_in_page_rule(
...@@ -77,7 +77,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -77,7 +77,7 @@ pub async fn get_next_server_transforms_rules(
} }
(false, Some(pages_dir)) (false, Some(pages_dir))
} }
ServerContextType::AppSSR { .. } => { ServerContextType::AppSSR { app_dir } => {
// Yah, this is SSR, but this is still treated as a Client transform layer. // Yah, this is SSR, but this is still treated as a Client transform layer.
// need to apply to foreign code too // need to apply to foreign code too
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
...@@ -85,10 +85,12 @@ pub async fn get_next_server_transforms_rules( ...@@ -85,10 +85,12 @@ pub async fn get_next_server_transforms_rules(
mdx_rs, mdx_rs,
)); ));
(false, None) (false, Some(app_dir))
} }
ServerContextType::AppRSC { ServerContextType::AppRSC {
client_transition, .. app_dir,
client_transition,
..
} => { } => {
rules.push(get_server_actions_transform_rule( rules.push(get_server_actions_transform_rule(
ActionsTransform::Server, ActionsTransform::Server,
...@@ -100,7 +102,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -100,7 +102,7 @@ pub async fn get_next_server_transforms_rules(
client_transition, client_transition,
)); ));
} }
(true, None) (true, Some(app_dir))
} }
ServerContextType::AppRoute { .. } => (false, None), ServerContextType::AppRoute { .. } => (false, None),
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => { ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
...@@ -110,7 +112,13 @@ pub async fn get_next_server_transforms_rules( ...@@ -110,7 +112,13 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code { if !foreign_code {
rules.push( rules.push(
get_next_dynamic_transform_rule(true, is_server_components, pages_dir, mode, mdx_rs) get_next_dynamic_transform_rule(
true,
is_server_components,
pages_or_app_dir,
mode,
mdx_rs,
)
.await?, .await?,
); );
......
...@@ -26,14 +26,14 @@ use crate::mode::NextMode; ...@@ -26,14 +26,14 @@ use crate::mode::NextMode;
pub async fn get_next_dynamic_transform_rule( pub async fn get_next_dynamic_transform_rule(
is_server_compiler: bool, is_server_compiler: bool,
is_react_server_layer: bool, is_react_server_layer: bool,
pages_dir: Option<Vc<FileSystemPath>>, pages_or_app_dir: Option<Vc<FileSystemPath>>,
mode: Vc<NextMode>, mode: Vc<NextMode>,
enable_mdx_rs: bool, enable_mdx_rs: bool,
) -> Result<ModuleRule> { ) -> Result<ModuleRule> {
let dynamic_transform = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextJsDynamic { let dynamic_transform = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextJsDynamic {
is_server_compiler, is_server_compiler,
is_react_server_layer, is_react_server_layer,
pages_dir: match pages_dir { pages_or_app_dir: match pages_or_app_dir {
None => None, None => None,
Some(path) => Some(path.await?.path.clone().into()), Some(path) => Some(path.await?.path.clone().into()),
}, },
...@@ -52,7 +52,7 @@ pub async fn get_next_dynamic_transform_rule( ...@@ -52,7 +52,7 @@ pub async fn get_next_dynamic_transform_rule(
struct NextJsDynamic { struct NextJsDynamic {
is_server_compiler: bool, is_server_compiler: bool,
is_react_server_layer: bool, is_react_server_layer: bool,
pages_dir: Option<PathBuf>, pages_or_app_dir: Option<PathBuf>,
mode: NextMode, mode: NextMode,
} }
...@@ -67,7 +67,7 @@ impl CustomTransformer for NextJsDynamic { ...@@ -67,7 +67,7 @@ impl CustomTransformer for NextJsDynamic {
false, false,
NextDynamicMode::Webpack, NextDynamicMode::Webpack,
FileName::Real(ctx.file_path_str.into()), FileName::Real(ctx.file_path_str.into()),
self.pages_dir.clone(), self.pages_or_app_dir.clone(),
)); ));
Ok(()) Ok(())
......
...@@ -217,7 +217,7 @@ where ...@@ -217,7 +217,7 @@ where
opts.prefer_esm, opts.prefer_esm,
NextDynamicMode::Webpack, NextDynamicMode::Webpack,
file.name.clone(), file.name.clone(),
opts.pages_dir.clone() opts.pages_dir.clone().or_else(|| opts.app_dir.clone()),
), ),
Optional::new( Optional::new(
crate::transforms::page_config::page_config(opts.is_development, opts.is_page_file), crate::transforms::page_config::page_config(opts.is_development, opts.is_page_file),
......
...@@ -28,14 +28,14 @@ pub fn next_dynamic( ...@@ -28,14 +28,14 @@ pub fn next_dynamic(
prefer_esm: bool, prefer_esm: bool,
mode: NextDynamicMode, mode: NextDynamicMode,
filename: FileName, filename: FileName,
pages_dir: Option<PathBuf>, pages_or_app_dir: Option<PathBuf>,
) -> impl Fold { ) -> impl Fold {
NextDynamicPatcher { NextDynamicPatcher {
is_development, is_development,
is_server_compiler, is_server_compiler,
is_react_server_layer, is_react_server_layer,
prefer_esm, prefer_esm,
pages_dir, pages_or_app_dir,
filename, filename,
dynamic_bindings: vec![], dynamic_bindings: vec![],
is_next_dynamic_first_arg: false, is_next_dynamic_first_arg: false,
...@@ -81,7 +81,7 @@ struct NextDynamicPatcher { ...@@ -81,7 +81,7 @@ struct NextDynamicPatcher {
is_server_compiler: bool, is_server_compiler: bool,
is_react_server_layer: bool, is_react_server_layer: bool,
prefer_esm: bool, prefer_esm: bool,
pages_dir: Option<PathBuf>, pages_or_app_dir: Option<PathBuf>,
filename: FileName, filename: FileName,
dynamic_bindings: Vec<Id>, dynamic_bindings: Vec<Id>,
is_next_dynamic_first_arg: bool, is_next_dynamic_first_arg: bool,
...@@ -216,6 +216,11 @@ impl Fold for NextDynamicPatcher { ...@@ -216,6 +216,11 @@ impl Fold for NextDynamicPatcher {
return expr; return expr;
}; };
let project_dir = match self.pages_or_app_dir.as_deref() {
Some(pages_or_app) => pages_or_app.parent(),
_ => None,
};
// dev client or server: // dev client or server:
// loadableGenerated: { // loadableGenerated: {
// modules: // modules:
...@@ -233,7 +238,7 @@ impl Fold for NextDynamicPatcher { ...@@ -233,7 +238,7 @@ impl Fold for NextDynamicPatcher {
"$left + $right" as Expr, "$left + $right" as Expr,
left: Expr = format!( left: Expr = format!(
"{} -> ", "{} -> ",
rel_filename(self.pages_dir.as_deref(), &self.filename) rel_filename(project_dir, &self.filename)
) )
.into(), .into(),
right: Expr = dynamically_imported_specifier.clone().into(), right: Expr = dynamically_imported_specifier.clone().into(),
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), { export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server" "src/some-file.js -> " + "../text-dynamic-no-ssr-server"
] ]
}, },
ssr: false ssr: false
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), { export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server" "src/some-file.js -> " + "../text-dynamic-no-ssr-server"
] ]
}, },
ssr: false ssr: false
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), { export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server" "src/some-file.js -> " + "../text-dynamic-no-ssr-server"
] ]
}, },
ssr: false ssr: false
......
import dynamic1 from 'next/dynamic'; import dynamic1 from 'next/dynamic';
import dynamic2 from 'next/dynamic'; import dynamic2 from 'next/dynamic';
const DynamicComponent1 = dynamic1(()=>import('../components/hello1') const DynamicComponent1 = dynamic1(()=>import('../components/hello1'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello1" "src/some-file.js -> " + "../components/hello1"
] ]
} }
}); });
const DynamicComponent2 = dynamic2(()=>import('../components/hello2') const DynamicComponent2 = dynamic2(()=>import('../components/hello2'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello2" "src/some-file.js -> " + "../components/hello2"
] ]
} }
}); });
import dynamic1 from 'next/dynamic'; import dynamic1 from 'next/dynamic';
import dynamic2 from 'next/dynamic'; import dynamic2 from 'next/dynamic';
const DynamicComponent1 = dynamic1(()=>import('../components/hello1') const DynamicComponent1 = dynamic1(()=>import('../components/hello1'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello1" "src/some-file.js -> " + "../components/hello1"
] ]
} }
}); });
const DynamicComponent2 = dynamic2(()=>import('../components/hello2') const DynamicComponent2 = dynamic2(()=>import('../components/hello2'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello2" "src/some-file.js -> " + "../components/hello2"
] ]
} }
}); });
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), { export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server" "src/some-file.js -> " + "../text-dynamic-no-ssr-server"
] ]
}, },
ssr: false ssr: false
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), { export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server" "src/some-file.js -> " + "../text-dynamic-no-ssr-server"
] ]
}, },
ssr: false ssr: false
......
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import somethingElse from 'something-else'; import somethingElse from 'something-else';
const DynamicComponent = dynamic(()=>import('../components/hello') const DynamicComponent = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
......
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
import somethingElse from 'something-else'; import somethingElse from 'something-else';
const DynamicComponent = dynamic(()=>import('../components/hello') const DynamicComponent = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
......
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import('../components/hello') const DynamicComponent = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import('../components/hello') const DynamicComponent = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import(`../components/hello`), { const DynamicComponent = dynamic(()=>import(`../components/hello`), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import(`../components/hello`), { const DynamicComponent = dynamic(()=>import(`../components/hello`), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
} }
}); });
......
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello') const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
loading: ()=><p >...</p> loading: ()=><p>...</p>
}); });
const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello') const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
ssr: false ssr: false
}); });
const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello') const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello'), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
ssr: false, ssr: false,
......
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello'), { const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
loading: ()=><p>...</p> loading: ()=><p>...</p>
...@@ -10,7 +10,7 @@ const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hell ...@@ -10,7 +10,7 @@ const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hell
const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), { const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
ssr: false ssr: false
...@@ -18,7 +18,7 @@ const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), { ...@@ -18,7 +18,7 @@ const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), {
const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello'), { const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello'), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "../components/hello" "src/some-file.js -> " + "../components/hello"
] ]
}, },
ssr: false, ssr: false,
......
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')) const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')), {
, {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "./components/hello" "src/some-file.js -> " + "./components/hello"
] ]
}, },
loading: ()=>null loading: ()=>null,
,
ssr: false ssr: false
}); });
...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic'; ...@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')), { const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')), {
loadableGenerated: { loadableGenerated: {
modules: [ modules: [
"some-file.js -> " + "./components/hello" "src/some-file.js -> " + "./components/hello"
] ]
}, },
loading: ()=>null, loading: ()=>null,
......
...@@ -260,7 +260,7 @@ function getFreshConfig( ...@@ -260,7 +260,7 @@ function getFreshConfig(
filename: string, filename: string,
inputSourceMap?: object | null inputSourceMap?: object | null
) { ) {
let { isServer, pagesDir, development, hasJsxRuntime, configFile } = let { isServer, pagesDir, development, hasJsxRuntime, configFile, cwd } =
loaderOptions loaderOptions
let customConfig: any = configFile let customConfig: any = configFile
...@@ -329,6 +329,7 @@ function getFreshConfig( ...@@ -329,6 +329,7 @@ function getFreshConfig(
supportsTopLevelAwait: true, supportsTopLevelAwait: true,
isServer, isServer,
cwd,
pagesDir, pagesDir,
isDev: development, isDev: development,
hasJsxRuntime, hasJsxRuntime,
......
...@@ -168,9 +168,9 @@ export default function ({ ...@@ -168,9 +168,9 @@ export default function ({
t.binaryExpression( t.binaryExpression(
'+', '+',
t.stringLiteral( t.stringLiteral(
(state.file.opts.caller?.pagesDir (state.file.opts.caller?.cwd
? relativePath( ? relativePath(
state.file.opts.caller.pagesDir, state.file.opts.caller.cwd,
state.file.opts.filename state.file.opts.filename
) )
: state.file.opts.filename) + ' -> ' : state.file.opts.filename) + ' -> '
......
...@@ -1737,6 +1737,7 @@ export default async function getBaseWebpackConfig( ...@@ -1737,6 +1737,7 @@ export default async function getBaseWebpackConfig(
new ReactLoadablePlugin({ new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST, filename: REACT_LOADABLE_MANIFEST,
pagesDir, pagesDir,
appDir,
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`, runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev, dev,
}), }),
......
...@@ -53,14 +53,12 @@ function getChunkGroupFromBlock( ...@@ -53,14 +53,12 @@ function getChunkGroupFromBlock(
function buildManifest( function buildManifest(
_compiler: webpack.Compiler, _compiler: webpack.Compiler,
compilation: webpack.Compilation, compilation: webpack.Compilation,
pagesDir: string | undefined, projectSrcDir: string | undefined,
dev: boolean dev: boolean
) { ) {
// If there's no pagesDir, output an empty manifest if (!projectSrcDir) {
if (!pagesDir) {
return {} return {}
} }
let manifest: { [k: string]: { id: string | number; files: string[] } } = {} let manifest: { [k: string]: { id: string | number; files: string[] } } = {}
// This is allowed: // This is allowed:
...@@ -91,7 +89,7 @@ function buildManifest( ...@@ -91,7 +89,7 @@ function buildManifest(
// We construct a "unique" key from origin module and request // We construct a "unique" key from origin module and request
// It's not perfect unique, but that will be fine for us. // It's not perfect unique, but that will be fine for us.
// We also need to construct the same in the babel plugin. // We also need to construct the same in the babel plugin.
const key = `${path.relative(pagesDir, originRequest)} -> ${ const key = `${path.relative(projectSrcDir, originRequest)} -> ${
dependency.request dependency.request
}` }`
...@@ -150,30 +148,34 @@ function buildManifest( ...@@ -150,30 +148,34 @@ function buildManifest(
export class ReactLoadablePlugin { export class ReactLoadablePlugin {
private filename: string private filename: string
private pagesDir?: string private pagesOrAppDir: string | undefined
private runtimeAsset?: string private runtimeAsset?: string
private dev: boolean private dev: boolean
constructor(opts: { constructor(opts: {
filename: string filename: string
pagesDir?: string pagesDir?: string
appDir?: string
runtimeAsset?: string runtimeAsset?: string
dev: boolean dev: boolean
}) { }) {
this.filename = opts.filename this.filename = opts.filename
this.pagesDir = opts.pagesDir this.pagesOrAppDir = opts.pagesDir || opts.appDir
this.runtimeAsset = opts.runtimeAsset this.runtimeAsset = opts.runtimeAsset
this.dev = opts.dev this.dev = opts.dev
} }
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
const projectSrcDir = this.pagesOrAppDir
? path.dirname(this.pagesOrAppDir)
: undefined
const manifest = buildManifest( const manifest = buildManifest(
compiler, compiler,
compilation, compilation,
this.pagesDir, projectSrcDir,
this.dev this.dev
) )
// @ts-ignore: TODO: remove when webpack 5 is stable
assets[this.filename] = new sources.RawSource( assets[this.filename] = new sources.RawSource(
JSON.stringify(manifest, null, 2) JSON.stringify(manifest, null, 2)
) )
......
...@@ -11,6 +11,8 @@ export interface RequestStore { ...@@ -11,6 +11,8 @@ export interface RequestStore {
readonly cookies: ReadonlyRequestCookies readonly cookies: ReadonlyRequestCookies
readonly mutableCookies: ResponseCookies readonly mutableCookies: ResponseCookies
readonly draftMode: DraftModeProvider readonly draftMode: DraftModeProvider
readonly reactLoadableManifest: Record<string, { files: string[] }>
readonly assetPrefix: string
} }
export type RequestAsyncStorage = AsyncLocalStorage<RequestStore> export type RequestAsyncStorage = AsyncLocalStorage<RequestStore>
......
...@@ -130,6 +130,8 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -130,6 +130,8 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
return cache.draftMode return cache.draftMode
}, },
reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '',
} }
return storage.run(store, callback, store) return storage.run(store, callback, store)
......
...@@ -19,6 +19,7 @@ export type DynamicOptions<P = {}> = LoadableGeneratedOptions & { ...@@ -19,6 +19,7 @@ export type DynamicOptions<P = {}> = LoadableGeneratedOptions & {
loading?: (loadingProps: DynamicOptionsLoadingProps) => JSX.Element | null loading?: (loadingProps: DynamicOptionsLoadingProps) => JSX.Element | null
loader?: Loader<P> loader?: Loader<P>
loadableGenerated?: LoadableGeneratedOptions loadableGenerated?: LoadableGeneratedOptions
modules?: string[]
ssr?: boolean ssr?: boolean
} }
...@@ -34,7 +35,7 @@ export default function dynamic<P = {}>( ...@@ -34,7 +35,7 @@ export default function dynamic<P = {}>(
dynamicOptions: DynamicOptions<P> | Loader<P>, dynamicOptions: DynamicOptions<P> | Loader<P>,
options?: DynamicOptions<P> options?: DynamicOptions<P>
): React.ComponentType<P> { ): React.ComponentType<P> {
const loadableOptions: LoadableOptions<P> = { let loadableOptions: LoadableOptions<P> = {
// A loading component is not required, so we default it // A loading component is not required, so we default it
loading: ({ error, isLoading, pastDelay }) => { loading: ({ error, isLoading, pastDelay }) => {
if (!pastDelay) return null if (!pastDelay) return null
...@@ -60,5 +61,13 @@ export default function dynamic<P = {}>( ...@@ -60,5 +61,13 @@ export default function dynamic<P = {}>(
loadableOptions.loader = dynamicOptions loadableOptions.loader = dynamicOptions
} }
return Loadable({ ...loadableOptions, ...options }) const mergedOptions = {
...loadableOptions,
...options,
}
return Loadable({
...mergedOptions,
modules: mergedOptions.loadableGenerated?.modules,
})
} }
import { Suspense, lazy } from 'react' import { Suspense, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr' import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types' import type { ComponentModule } from './types'
import { PreloadCss } from './preload-css'
// Normalize loader to return the module as form { default: Component } for `React.lazy`. // Normalize loader to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader // Also for backward compatible since next/dynamic allows to resolve a component directly with loader
...@@ -34,6 +35,7 @@ interface LoadableOptions { ...@@ -34,6 +35,7 @@ interface LoadableOptions {
loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>> loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>>
loading?: React.ComponentType<any> | null loading?: React.ComponentType<any> | null
ssr?: boolean ssr?: boolean
modules?: string[]
} }
function Loadable(options: LoadableOptions) { function Loadable(options: LoadableOptions) {
...@@ -47,7 +49,13 @@ function Loadable(options: LoadableOptions) { ...@@ -47,7 +49,13 @@ function Loadable(options: LoadableOptions) {
) : null ) : null
const children = opts.ssr ? ( const children = opts.ssr ? (
<>
{/* During SSR, we need to preload the CSS from the dynamic component to avoid flash of unstyled content */}
{typeof window === 'undefined' ? (
<PreloadCss moduleIds={opts.modules} />
) : null}
<Lazy {...props} /> <Lazy {...props} />
</>
) : ( ) : (
<BailoutToCSR reason="next/dynamic"> <BailoutToCSR reason="next/dynamic">
<Lazy {...props} /> <Lazy {...props} />
......
'use client'
export function PreloadCss({ moduleIds }: { moduleIds: string[] | undefined }) {
// Early return in client compilation and only load requestStore on server side
if (typeof window !== 'undefined') {
return null
}
const {
getExpectedRequestStore,
} = require('../../../client/components/request-async-storage.external')
const requestStore = getExpectedRequestStore()
const allFiles = []
// Search the current dynamic call unique key id in react loadable manifest,
// and find the corresponding CSS files to preload
if (requestStore.reactLoadableManifest && moduleIds) {
const manifest = requestStore.reactLoadableManifest
for (const key of moduleIds) {
if (!manifest[key]) continue
const cssFiles = manifest[key].files.filter((file: string) =>
file.endsWith('.css')
)
allFiles.push(...cssFiles)
}
}
if (allFiles.length === 0) {
return null
}
return (
<>
{allFiles.map((file) => {
return (
<link
key={file}
// @ts-ignore
precedence={'dynamic'}
rel="stylesheet"
href={`${requestStore.assetPrefix}/_next/${encodeURI(file)}`}
as="style"
/>
)
})}
</>
)
}
...@@ -6,11 +6,9 @@ export declare type LoaderComponent<P = {}> = Promise< ...@@ -6,11 +6,9 @@ export declare type LoaderComponent<P = {}> = Promise<
export declare type Loader<P = {}> = () => LoaderComponent<P> export declare type Loader<P = {}> = () => LoaderComponent<P>
export type LoaderMap = { [module: string]: () => Loader<any> }
export type LoadableGeneratedOptions = { export type LoadableGeneratedOptions = {
webpack?(): any webpack?(): any
modules?(): LoaderMap modules?: string[]
} }
export type DynamicOptionsLoadingProps = { export type DynamicOptionsLoadingProps = {
......
...@@ -75,7 +75,7 @@ describe.each([ ...@@ -75,7 +75,7 @@ describe.each([
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect( expect(
JSON.parse($('#__NEXT_DATA__').html()).dynamicIds JSON.parse($('#__NEXT_DATA__').html()).dynamicIds
).toContain('dynamic/ssr.js -> ../../components/hello1') ).toContain('pages/dynamic/ssr.js -> ../../components/hello1')
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
...@@ -84,7 +84,9 @@ describe.each([ ...@@ -84,7 +84,9 @@ describe.each([
// Make sure the client side knows it has to wait for the bundle // Make sure the client side knows it has to wait for the bundle
expect( expect(
JSON.parse($('#__NEXT_DATA__').html()).dynamicIds JSON.parse($('#__NEXT_DATA__').html()).dynamicIds
).toContain('dynamic/function.js -> ../../components/hello1') ).toContain(
'pages/dynamic/function.js -> ../../components/hello1'
)
expect($('body').text()).toMatch(/Hello World 1/) expect($('body').text()).toMatch(/Hello World 1/)
}) })
......
...@@ -40,7 +40,7 @@ export default (context, env) => { ...@@ -40,7 +40,7 @@ export default (context, env) => {
const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html()) const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html())
if (env === 'dev') { if (env === 'dev') {
expect(dynamicIds).toContain(`${page}.js -> ../components/foo`) expect(dynamicIds).toContain(`pages/${page}.js -> ../components/foo`)
} else { } else {
expect(dynamicIds.length).toBe(1) expect(dynamicIds.length).toBe(1)
} }
......
'use client'
import dynamicApi from 'next/dynamic'
const AsyncBar = dynamicApi(() => import('../../components/bar'))
export default function Page() {
return <AsyncBar />
}
export const dynamic = 'force-dynamic'
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<Link id="ssr" href="/ssr">
SSR
</Link>
</div>
)
}
'use client'
import dynamicApi from 'next/dynamic'
const AsyncFoo = dynamicApi(() => import('../../components/foo'))
export default function Page() {
return <AsyncFoo />
}
export const dynamic = 'force-dynamic'
import './bar.css'
export default function Bar() {
return <p className="text">bar</p>
}
import './foo.css'
export default function Foo() {
return <p className="text">foo</p>
}
import { createNextDescribe } from 'e2e-utils'
import { retry } from 'next-test-utils'
createNextDescribe(
'app dir - dynamic css',
{
files: __dirname,
skipDeployment: true,
},
({ next }) => {
it('should preload css of dynamic component during SSR', async () => {
const $ = await next.render$('/ssr')
const cssLinks = $('link[rel="stylesheet"]')
expect(cssLinks.attr('href')).toContain('.css')
})
it('should only apply corresponding css for page loaded that /ssr', async () => {
const browser = await next.browser('/ssr')
await retry(async () => {
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('.text')).color`
)
).toBe('rgb(255, 0, 0)')
// Default border width, which is not effected by bar.css that is not loaded in /ssr
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('.text')).borderWidth`
)
).toBe('0px')
})
})
it('should only apply corresponding css for page loaded that /another', async () => {
const browser = await next.browser('/another')
await retry(async () => {
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('.text')).color`
)
).not.toBe('rgb(255, 0, 0)')
// Default border width, which is not effected by bar.css that is not loaded in /ssr
expect(
await browser.eval(
`window.getComputedStyle(document.querySelector('.text')).borderWidth`
)
).toBe('1px')
})
})
}
)
...@@ -14515,6 +14515,12 @@ ...@@ -14515,6 +14515,12 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/production/app-dir/dynamic-css/index.test.ts": {
"passed": [],
"failed": [
"app dir - dynamic css should preload css of dynamic component during SSR"
]
},
"test/production/app-dir-edge-runtime-with-wasm/index.test.ts": { "test/production/app-dir-edge-runtime-with-wasm/index.test.ts": {
"passed": ["app-dir edge runtime with wasm should have built"], "passed": ["app-dir edge runtime with wasm should have built"],
"failed": [], "failed": [],
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