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 {
) -> Result<Vc<OutputAssets>> {
let this = self.await?;
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?;
......@@ -937,12 +937,12 @@ impl PageEndpoint {
let chunk_output = chunk_output.await?;
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
// For the pages dir, next_dynamic transform puts relative paths to the pages
// https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/react-loadable-plugin.ts
// next_dynamic transform puts relative paths to the project dir
// dir for the origin import.
let id = format!(
"{} -> {}",
pages_dir
project_src_dir
.get_path_to(origin_path)
.map_or_else(|| origin_path.to_string(), |path| path.to_string()),
import
......
......@@ -40,7 +40,7 @@ pub async fn get_next_client_transforms_rules(
let mdx_rs = *next_config.mdx_rs().await?;
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 } => {
if !foreign_code {
rules.push(
......@@ -59,12 +59,12 @@ pub async fn get_next_client_transforms_rules(
}
Some(pages_dir)
}
ClientContextType::App { .. } => {
ClientContextType::App { app_dir } => {
rules.push(get_server_actions_transform_rule(
ActionsTransform::Client,
mdx_rs,
));
None
Some(app_dir)
}
ClientContextType::Fallback | ClientContextType::Other => None,
};
......@@ -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_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_page_static_info_assert_rule(
......
......@@ -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 } => {
if !foreign_code {
rules.push(get_next_disallow_export_all_in_page_rule(
......@@ -77,7 +77,7 @@ pub async fn get_next_server_transforms_rules(
}
(false, Some(pages_dir))
}
ServerContextType::AppSSR { .. } => {
ServerContextType::AppSSR { app_dir } => {
// Yah, this is SSR, but this is still treated as a Client transform layer.
// need to apply to foreign code too
rules.push(get_server_actions_transform_rule(
......@@ -85,10 +85,12 @@ pub async fn get_next_server_transforms_rules(
mdx_rs,
));
(false, None)
(false, Some(app_dir))
}
ServerContextType::AppRSC {
client_transition, ..
app_dir,
client_transition,
..
} => {
rules.push(get_server_actions_transform_rule(
ActionsTransform::Server,
......@@ -100,7 +102,7 @@ pub async fn get_next_server_transforms_rules(
client_transition,
));
}
(true, None)
(true, Some(app_dir))
}
ServerContextType::AppRoute { .. } => (false, None),
ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
......@@ -110,8 +112,14 @@ pub async fn get_next_server_transforms_rules(
if !foreign_code {
rules.push(
get_next_dynamic_transform_rule(true, is_server_components, pages_dir, mode, mdx_rs)
.await?,
get_next_dynamic_transform_rule(
true,
is_server_components,
pages_or_app_dir,
mode,
mdx_rs,
)
.await?,
);
rules.push(get_next_amp_attr_rule(mdx_rs));
......
......@@ -26,14 +26,14 @@ use crate::mode::NextMode;
pub async fn get_next_dynamic_transform_rule(
is_server_compiler: bool,
is_react_server_layer: bool,
pages_dir: Option<Vc<FileSystemPath>>,
pages_or_app_dir: Option<Vc<FileSystemPath>>,
mode: Vc<NextMode>,
enable_mdx_rs: bool,
) -> Result<ModuleRule> {
let dynamic_transform = EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextJsDynamic {
is_server_compiler,
is_react_server_layer,
pages_dir: match pages_dir {
pages_or_app_dir: match pages_or_app_dir {
None => None,
Some(path) => Some(path.await?.path.clone().into()),
},
......@@ -52,7 +52,7 @@ pub async fn get_next_dynamic_transform_rule(
struct NextJsDynamic {
is_server_compiler: bool,
is_react_server_layer: bool,
pages_dir: Option<PathBuf>,
pages_or_app_dir: Option<PathBuf>,
mode: NextMode,
}
......@@ -67,7 +67,7 @@ impl CustomTransformer for NextJsDynamic {
false,
NextDynamicMode::Webpack,
FileName::Real(ctx.file_path_str.into()),
self.pages_dir.clone(),
self.pages_or_app_dir.clone(),
));
Ok(())
......
......@@ -217,7 +217,7 @@ where
opts.prefer_esm,
NextDynamicMode::Webpack,
file.name.clone(),
opts.pages_dir.clone()
opts.pages_dir.clone().or_else(|| opts.app_dir.clone()),
),
Optional::new(
crate::transforms::page_config::page_config(opts.is_development, opts.is_page_file),
......
......@@ -28,14 +28,14 @@ pub fn next_dynamic(
prefer_esm: bool,
mode: NextDynamicMode,
filename: FileName,
pages_dir: Option<PathBuf>,
pages_or_app_dir: Option<PathBuf>,
) -> impl Fold {
NextDynamicPatcher {
is_development,
is_server_compiler,
is_react_server_layer,
prefer_esm,
pages_dir,
pages_or_app_dir,
filename,
dynamic_bindings: vec![],
is_next_dynamic_first_arg: false,
......@@ -81,7 +81,7 @@ struct NextDynamicPatcher {
is_server_compiler: bool,
is_react_server_layer: bool,
prefer_esm: bool,
pages_dir: Option<PathBuf>,
pages_or_app_dir: Option<PathBuf>,
filename: FileName,
dynamic_bindings: Vec<Id>,
is_next_dynamic_first_arg: bool,
......@@ -216,6 +216,11 @@ impl Fold for NextDynamicPatcher {
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:
// loadableGenerated: {
// modules:
......@@ -233,7 +238,7 @@ impl Fold for NextDynamicPatcher {
"$left + $right" as Expr,
left: Expr = format!(
"{} -> ",
rel_filename(self.pages_dir.as_deref(), &self.filename)
rel_filename(project_dir, &self.filename)
)
.into(),
right: Expr = dynamically_imported_specifier.clone().into(),
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server"
"src/some-file.js -> " + "../text-dynamic-no-ssr-server"
]
},
ssr: false
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server"
"src/some-file.js -> " + "../text-dynamic-no-ssr-server"
]
},
ssr: false
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server"
"src/some-file.js -> " + "../text-dynamic-no-ssr-server"
]
},
ssr: false
......
import dynamic1 from 'next/dynamic';
import dynamic2 from 'next/dynamic';
const DynamicComponent1 = dynamic1(()=>import('../components/hello1')
, {
const DynamicComponent1 = dynamic1(()=>import('../components/hello1'), {
loadableGenerated: {
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: {
modules: [
"some-file.js -> " + "../components/hello2"
"src/some-file.js -> " + "../components/hello2"
]
}
});
import dynamic1 from 'next/dynamic';
import dynamic2 from 'next/dynamic';
const DynamicComponent1 = dynamic1(()=>import('../components/hello1')
, {
const DynamicComponent1 = dynamic1(()=>import('../components/hello1'), {
loadableGenerated: {
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: {
modules: [
"some-file.js -> " + "../components/hello2"
"src/some-file.js -> " + "../components/hello2"
]
}
});
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server"
"src/some-file.js -> " + "../text-dynamic-no-ssr-server"
]
},
ssr: false
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
export const NextDynamicNoSSRServerComponent = dynamic(()=>import('../text-dynamic-no-ssr-server'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../text-dynamic-no-ssr-server"
"src/some-file.js -> " + "../text-dynamic-no-ssr-server"
]
},
ssr: false
......
import dynamic from 'next/dynamic';
import somethingElse from 'something-else';
const DynamicComponent = dynamic(()=>import('../components/hello')
, {
const DynamicComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
......
import dynamic from 'next/dynamic';
import somethingElse from 'something-else';
const DynamicComponent = dynamic(()=>import('../components/hello')
, {
const DynamicComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
......
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import('../components/hello')
, {
const DynamicComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import('../components/hello')
, {
const DynamicComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import(`../components/hello`), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>import(`../components/hello`), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
}
});
......
import dynamic from 'next/dynamic';
const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello')
, {
const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
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: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
},
ssr: false
});
const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello')
, {
const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
},
ssr: false,
......
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
},
loading: ()=><p>...</p>
......@@ -10,7 +10,7 @@ const DynamicComponentWithCustomLoading = dynamic(()=>import('../components/hell
const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
},
ssr: false
......@@ -18,7 +18,7 @@ const DynamicClientOnlyComponent = dynamic(()=>import('../components/hello'), {
const DynamicClientOnlyComponentWithSuspense = dynamic(()=>import('../components/hello'), {
loadableGenerated: {
modules: [
"some-file.js -> " + "../components/hello"
"src/some-file.js -> " + "../components/hello"
]
},
ssr: false,
......
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>handleImport(import('./components/hello'))
, {
const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')), {
loadableGenerated: {
modules: [
"some-file.js -> " + "./components/hello"
"src/some-file.js -> " + "./components/hello"
]
},
loading: ()=>null
,
loading: ()=>null,
ssr: false
});
......@@ -2,7 +2,7 @@ import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(()=>handleImport(import('./components/hello')), {
loadableGenerated: {
modules: [
"some-file.js -> " + "./components/hello"
"src/some-file.js -> " + "./components/hello"
]
},
loading: ()=>null,
......
......@@ -260,7 +260,7 @@ function getFreshConfig(
filename: string,
inputSourceMap?: object | null
) {
let { isServer, pagesDir, development, hasJsxRuntime, configFile } =
let { isServer, pagesDir, development, hasJsxRuntime, configFile, cwd } =
loaderOptions
let customConfig: any = configFile
......@@ -329,6 +329,7 @@ function getFreshConfig(
supportsTopLevelAwait: true,
isServer,
cwd,
pagesDir,
isDev: development,
hasJsxRuntime,
......
......@@ -168,9 +168,9 @@ export default function ({
t.binaryExpression(
'+',
t.stringLiteral(
(state.file.opts.caller?.pagesDir
(state.file.opts.caller?.cwd
? relativePath(
state.file.opts.caller.pagesDir,
state.file.opts.caller.cwd,
state.file.opts.filename
)
: state.file.opts.filename) + ' -> '
......
......@@ -1737,6 +1737,7 @@ export default async function getBaseWebpackConfig(
new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST,
pagesDir,
appDir,
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev,
}),
......
......@@ -53,14 +53,12 @@ function getChunkGroupFromBlock(
function buildManifest(
_compiler: webpack.Compiler,
compilation: webpack.Compilation,
pagesDir: string | undefined,
projectSrcDir: string | undefined,
dev: boolean
) {
// If there's no pagesDir, output an empty manifest
if (!pagesDir) {
if (!projectSrcDir) {
return {}
}
let manifest: { [k: string]: { id: string | number; files: string[] } } = {}
// This is allowed:
......@@ -91,7 +89,7 @@ function buildManifest(
// We construct a "unique" key from origin module and request
// It's not perfect unique, but that will be fine for us.
// 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
}`
......@@ -150,30 +148,34 @@ function buildManifest(
export class ReactLoadablePlugin {
private filename: string
private pagesDir?: string
private pagesOrAppDir: string | undefined
private runtimeAsset?: string
private dev: boolean
constructor(opts: {
filename: string
pagesDir?: string
appDir?: string
runtimeAsset?: string
dev: boolean
}) {
this.filename = opts.filename
this.pagesDir = opts.pagesDir
this.pagesOrAppDir = opts.pagesDir || opts.appDir
this.runtimeAsset = opts.runtimeAsset
this.dev = opts.dev
}
createAssets(compiler: any, compilation: any, assets: any) {
const projectSrcDir = this.pagesOrAppDir
? path.dirname(this.pagesOrAppDir)
: undefined
const manifest = buildManifest(
compiler,
compilation,
this.pagesDir,
projectSrcDir,
this.dev
)
// @ts-ignore: TODO: remove when webpack 5 is stable
assets[this.filename] = new sources.RawSource(
JSON.stringify(manifest, null, 2)
)
......
......@@ -11,6 +11,8 @@ export interface RequestStore {
readonly cookies: ReadonlyRequestCookies
readonly mutableCookies: ResponseCookies
readonly draftMode: DraftModeProvider
readonly reactLoadableManifest: Record<string, { files: string[] }>
readonly assetPrefix: string
}
export type RequestAsyncStorage = AsyncLocalStorage<RequestStore>
......
......@@ -130,6 +130,8 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
return cache.draftMode
},
reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '',
}
return storage.run(store, callback, store)
......
......@@ -19,6 +19,7 @@ export type DynamicOptions<P = {}> = LoadableGeneratedOptions & {
loading?: (loadingProps: DynamicOptionsLoadingProps) => JSX.Element | null
loader?: Loader<P>
loadableGenerated?: LoadableGeneratedOptions
modules?: string[]
ssr?: boolean
}
......@@ -34,7 +35,7 @@ export default function dynamic<P = {}>(
dynamicOptions: DynamicOptions<P> | Loader<P>,
options?: DynamicOptions<P>
): React.ComponentType<P> {
const loadableOptions: LoadableOptions<P> = {
let loadableOptions: LoadableOptions<P> = {
// A loading component is not required, so we default it
loading: ({ error, isLoading, pastDelay }) => {
if (!pastDelay) return null
......@@ -60,5 +61,13 @@ export default function dynamic<P = {}>(
loadableOptions.loader = dynamicOptions
}
return Loadable({ ...loadableOptions, ...options })
const mergedOptions = {
...loadableOptions,
...options,
}
return Loadable({
...mergedOptions,
modules: mergedOptions.loadableGenerated?.modules,
})
}
import { Suspense, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadCss } from './preload-css'
// 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
......@@ -34,6 +35,7 @@ interface LoadableOptions {
loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>>
loading?: React.ComponentType<any> | null
ssr?: boolean
modules?: string[]
}
function Loadable(options: LoadableOptions) {
......@@ -47,7 +49,13 @@ function Loadable(options: LoadableOptions) {
) : null
const children = opts.ssr ? (
<Lazy {...props} />
<>
{/* 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} />
</>
) : (
<BailoutToCSR reason="next/dynamic">
<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<
export declare type Loader<P = {}> = () => LoaderComponent<P>
export type LoaderMap = { [module: string]: () => Loader<any> }
export type LoadableGeneratedOptions = {
webpack?(): any
modules?(): LoaderMap
modules?: string[]
}
export type DynamicOptionsLoadingProps = {
......
......@@ -75,7 +75,7 @@ describe.each([
// Make sure the client side knows it has to wait for the bundle
expect(
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/)
})
......@@ -84,7 +84,9 @@ describe.each([
// Make sure the client side knows it has to wait for the bundle
expect(
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/)
})
......
......@@ -40,7 +40,7 @@ export default (context, env) => {
const { dynamicIds } = JSON.parse($('#__NEXT_DATA__').html())
if (env === 'dev') {
expect(dynamicIds).toContain(`${page}.js -> ../components/foo`)
expect(dynamicIds).toContain(`pages/${page}.js -> ../components/foo`)
} else {
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 @@
"flakey": [],
"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": {
"passed": ["app-dir edge runtime with wasm should have built"],
"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