Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
devjiwonchoi committed Aug 27, 2024
1 parent ffe1cf9 commit 459986a
Showing 1 changed file with 17 additions and 21 deletions.
38 changes: 17 additions & 21 deletions packages/next/src/build/webpack/plugins/build-manifest-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,23 @@ export default class BuildManifestPlugin {
assetMap.pages[pagePath] = [...new Set([...mainFiles, ...filesForPage])]
}

// When a CSS file is server-rendered, it is cleaned up during
// Link transitions. If the target route dynamically imports
// the same CSS file, the client will skip loading it
// (as it was already loaded statically), but still clean it up
// during transition. This can result in missing CSS styles.
// x-ref: `next/src/client/index.tsx`

// 1. page transition
// 2. import (CSS already exists)
// 3. clean up server-rendered CSS
// 4. CSS is missing

// To prevent this, we add the dynamically imported CSS files
// to the build manifest to signal the client not to clean up
// the CSS file if it's loaded dynamically, preserving the styles.

/* Inspired by `next/src/build/webpack/react-loadable-plugin.ts` */
// When a CSS file is loaded both dynamically and statically,
// the file will be "unloaded" during the page Link transition.
// This is because the CSS file was included in the build manifest,
// but as we the "dynamic import" is processed before we tell the
// browser to unload the CSS file, the CSS file is not loaded.
// Therefore we add
const _handleBlock = (block: any) => {
block.blocks.forEach(_handleBlock)

Expand All @@ -303,7 +313,7 @@ export default class BuildManifestPlugin {
}

for (const dependency of block.dependencies) {
// We target the two types of import() dependencies:
// We target the two types of dynamic import() dependencies:
// `ImportDependency` and `ContextElementDependency`.

// ImportDependency:
Expand All @@ -317,9 +327,6 @@ export default class BuildManifestPlugin {
const parentModule =
compilation.moduleGraph.getParentModule(dependency)

// origin of the import() call
const importOrigin = parentModule?.resource

const parentChunks =
compilation.chunkGraph.getModuleChunks(parentModule)

Expand All @@ -334,17 +341,6 @@ export default class BuildManifestPlugin {
// We should already have `assetMapPages` from the `entrypoint`.
if (!assetMapPages) continue

// If the `importOrigin` exists, the file will already be included
// in the block chunk groups. Otherwise, we will look for the
// parent module chunks for the files.
if (!importOrigin) {
chunk.files.forEach((file: string) => {
if (file.endsWith('.css') && file.match(/^static\/css\//)) {
dynamicCSSFiles.add(file)
}
})
}

assetMap.pages[pagePath] = [
...new Set([...assetMapPages, ...dynamicCSSFiles]),
]
Expand Down

0 comments on commit 459986a

Please sign in to comment.