Unverified Commit 9d67a9f2 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

partially fix css duplication in app dir (#61198)

### What?

depends on https://github.com/facebook/react/pull/28108

* fixes CSS Ordering issues due to CSS duplication in production mode
* The issues still happen in dev mode
* Highlights broken CSS Ordering for more dev cases, e. g. CSS in client
components


Closes PACK-2300
parent 72826823
...@@ -966,6 +966,73 @@ export default async function getBaseWebpackConfig( ...@@ -966,6 +966,73 @@ export default async function getBaseWebpackConfig(
} }
} }
const frameworkCacheGroup = {
chunks: 'all' as const,
name: 'framework',
// Ensures the framework chunk is not created for App Router.
layer: isWebpackDefaultLayer,
test(module: any) {
const resource = module.nameForCondition?.()
return resource
? topLevelFrameworkPaths.some((pkgPath) =>
resource.startsWith(pkgPath)
)
: false
},
priority: 40,
// Don't let webpack eliminate this chunk (prevents this chunk from
// becoming a part of the commons chunk)
enforce: true,
}
const libCacheGroup = {
test(module: {
size: Function
nameForCondition: Function
}): boolean {
return (
module.size() > 160000 &&
/node_modules[/\\]/.test(module.nameForCondition() || '')
)
},
name(module: {
layer: string | null | undefined
type: string
libIdent?: Function
updateHash: (hash: crypto.Hash) => void
}): string {
const hash = crypto.createHash('sha1')
if (isModuleCSS(module)) {
module.updateHash(hash)
} else {
if (!module.libIdent) {
throw new Error(
`Encountered unknown module type: ${module.type}. Please open an issue.`
)
}
hash.update(module.libIdent({ context: dir }))
}
// Ensures the name of the chunk is not the same between two modules in different layers
// E.g. if you import 'button-library' in App Router and Pages Router we don't want these to be bundled in the same chunk
// as they're never used on the same page.
if (module.layer) {
hash.update(module.layer)
}
return hash.digest('hex').substring(0, 8)
},
priority: 30,
minChunks: 1,
reuseExistingChunk: true,
}
const cssCacheGroup = {
test: /\.(css|sass|scss)$/i,
chunks: 'all' as const,
enforce: true,
type: /css/,
minChunks: 2,
priority: 100,
}
return { return {
// Keep main and _app chunks unsplitted in webpack 5 // Keep main and _app chunks unsplitted in webpack 5
// as we don't need a separate vendor chunk from that // as we don't need a separate vendor chunk from that
...@@ -973,67 +1040,16 @@ export default async function getBaseWebpackConfig( ...@@ -973,67 +1040,16 @@ export default async function getBaseWebpackConfig(
// duplication that need to be pulled out. // duplication that need to be pulled out.
chunks: (chunk: any) => chunks: (chunk: any) =>
!/^(polyfills|main|pages\/_app)$/.test(chunk.name), !/^(polyfills|main|pages\/_app)$/.test(chunk.name),
cacheGroups: { cacheGroups: appDir
framework: { ? {
chunks: 'all', css: cssCacheGroup,
name: 'framework', framework: frameworkCacheGroup,
// Ensures the framework chunk is not created for App Router. lib: libCacheGroup,
layer: isWebpackDefaultLayer, }
test(module: any) { : {
const resource = module.nameForCondition?.() framework: frameworkCacheGroup,
return resource lib: libCacheGroup,
? topLevelFrameworkPaths.some((pkgPath) =>
resource.startsWith(pkgPath)
)
: false
},
priority: 40,
// Don't let webpack eliminate this chunk (prevents this chunk from
// becoming a part of the commons chunk)
enforce: true,
},
lib: {
test(module: {
size: Function
nameForCondition: Function
}): boolean {
return (
module.size() > 160000 &&
/node_modules[/\\]/.test(module.nameForCondition() || '')
)
},
name(module: {
layer: string | null | undefined
type: string
libIdent?: Function
updateHash: (hash: crypto.Hash) => void
}): string {
const hash = crypto.createHash('sha1')
if (isModuleCSS(module)) {
module.updateHash(hash)
} else {
if (!module.libIdent) {
throw new Error(
`Encountered unknown module type: ${module.type}. Please open an issue.`
)
}
hash.update(module.libIdent({ context: dir }))
}
// Ensures the name of the chunk is not the same between two modules in different layers
// E.g. if you import 'button-library' in App Router and Pages Router we don't want these to be bundled in the same chunk
// as they're never used on the same page.
if (module.layer) {
hash.update(module.layer)
}
return hash.digest('hex').substring(0, 8)
}, },
priority: 30,
minChunks: 1,
reuseExistingChunk: true,
},
},
maxInitialRequests: 25, maxInitialRequests: 25,
minSize: 20000, minSize: 20000,
} }
......
$base1: rgb(255, 1, 0);
.base {
color: $base1;
}
.base {
color: rgb(255, 0, 0);
}
'use client'
import Link from 'next/link'
import baseStyle from '../base2.module.css'
import baseStyle2 from '../base2-scss.module.scss'
import style from './style.module.css'
export default function Page() {
return (
<div>
<p
className={`${style.name} ${baseStyle.base} ${baseStyle2.base}`}
id="hello1c"
>
hello world
</p>
<Link href={'/first'} id="first">
First
</Link>
<Link href={'/first-client'} id="first-client">
First client
</Link>
<Link href={'/second'} id="second">
Second
</Link>
<Link href={'/second-client'} id="second-client">
Second client
</Link>
<Link href={'/third'} id="third">
Third
</Link>
</div>
)
}
.name {
composes: base from '../base.module.css';
color: rgb(255, 0, 255);
}
import Link from 'next/link'
import baseStyle from '../base2.module.css'
import baseStyle2 from '../base2-scss.module.scss'
import style from './style.module.css'
export default function Page() {
return (
<div>
<p
className={`${style.name} ${baseStyle.base} ${baseStyle2.base}`}
id="hello1"
>
hello world
</p>
<Link href={'/first'} id="first">
First
</Link>
<Link href={'/first-client'} id="first-client">
First client
</Link>
<Link href={'/second'} id="second">
Second
</Link>
<Link href={'/second-client'} id="second-client">
Second client
</Link>
<Link href={'/third'} id="third">
Third
</Link>
</div>
)
}
.name {
composes: base from '../base.module.css';
color: blue;
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<p>hello world</p>
<Link href={'/first'}>First</Link>
<Link href={'/second'}>Second</Link>
</div>
)
}
'use client'
import Link from 'next/link'
import baseStyle from '../base2.module.css'
import baseStyle2 from '../base2-scss.module.scss'
import style from './style.module.css'
export default function Page() {
return (
<div>
<p
className={`${style.name} ${baseStyle.base} ${baseStyle2.base}`}
id="hello2c"
>
hello world
</p>
<Link href={'/first'} id="first">
First
</Link>
<Link href={'/first-client'} id="first-client">
First client
</Link>
<Link href={'/second'} id="second">
Second
</Link>
<Link href={'/second-client'} id="second-client">
Second client
</Link>
<Link href={'/third'} id="third">
Third
</Link>
</div>
)
}
.name {
composes: base from '../base.module.css';
color: rgb(255, 128, 0);
}
import Link from 'next/link'
import baseStyle from '../base2.module.css'
import baseStyle2 from '../base2-scss.module.scss'
import style from './style.module.scss'
export default function Page() {
return (
<div>
<p
className={`${style.name} ${baseStyle.base} ${baseStyle2.base}`}
id="hello2"
>
hello world
</p>
<Link href={'/first'} id="first">
First
</Link>
<Link href={'/first-client'} id="first-client">
First client
</Link>
<Link href={'/second'} id="second">
Second
</Link>
<Link href={'/second-client'} id="second-client">
Second client
</Link>
<Link href={'/third'} id="third">
Third
</Link>
</div>
)
}
.name {
composes: base from '../base-scss.module.scss';
color: green;
}
import Link from 'next/link'
import baseStyle from '../base2.module.css'
import baseStyle2 from '../base2-scss.module.scss'
import style from './style.module.scss'
export default function Page() {
return (
<div>
<p
className={`${style.name} ${baseStyle.base} ${baseStyle2.base}`}
id="hello3"
>
hello world
</p>
<Link href={'/first'} id="first">
First
</Link>
<Link href={'/first-client'} id="first-client">
First client
</Link>
<Link href={'/second'} id="second">
Second
</Link>
<Link href={'/second-client'} id="second-client">
Second client
</Link>
<Link href={'/third'} id="third">
Third
</Link>
</div>
)
}
.name {
composes: base from '../base-scss.module.scss';
color: rgb(0, 128, 128);
}
import { createNextDescribe } from 'e2e-utils'
function getPairs(all) {
const result = []
for (const first of all) {
for (const second of all) {
if (first === second) {
continue
}
result.push([first, second])
}
}
return result
}
const PAGES = {
first: {
url: '/first',
selector: '#hello1',
color: 'rgb(0, 0, 255)',
},
second: {
url: '/second',
selector: '#hello2',
color: 'rgb(0, 128, 0)',
},
third: {
url: '/third',
selector: '#hello3',
color: 'rgb(0, 128, 128)',
},
'first-client': {
url: '/first-client',
selector: '#hello1c',
color: 'rgb(255, 0, 255)',
},
'second-client': {
url: '/second-client',
selector: '#hello2c',
color: 'rgb(255, 128, 0)',
},
}
const allPairs = getPairs(Object.keys(PAGES))
createNextDescribe(
'css-order',
{
files: __dirname,
dependencies: {
sass: 'latest',
},
},
({ next, isNextDev, isTurbopack }) => {
for (const ordering of allPairs) {
const name = `should load correct styles navigating back again ${ordering.join(
' -> '
)} -> ${ordering.join(' -> ')}`
// TODO fix this case
const broken = isNextDev
if (broken) {
it.todo(name)
continue
}
it(name, async () => {
const start = PAGES[ordering[0]]
const browser = await next.browser(start.url)
const check = async (pageInfo) => {
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
}
const navigate = async (page) => {
await browser.waitForElementByCss('#' + page).click()
}
await check(start)
for (const page of ordering.slice(1)) {
await navigate(page)
await check(PAGES[page])
}
for (const page of ordering) {
await navigate(page)
await check(PAGES[page])
}
})
}
for (const ordering of allPairs) {
const name = `should load correct styles navigating ${ordering.join(
' -> '
)}`
// TODO fix this case
const broken =
isNextDev &&
!isTurbopack &&
ordering.some(
(page) => page.includes('client') || page.includes('first')
)
if (broken) {
it.todo(name)
continue
}
it(name, async () => {
const start = PAGES[ordering[0]]
const browser = await next.browser(start.url)
const check = async (pageInfo) => {
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
}
const navigate = async (page) => {
await browser.waitForElementByCss('#' + page).click()
}
await check(start)
for (const page of ordering.slice(1)) {
await navigate(page)
await check(PAGES[page])
}
})
}
for (const [page, pageInfo] of Object.entries(PAGES)) {
const name = `should load correct styles on ${page}`
// TODO fix this case
const broken = isNextDev && !isTurbopack && page.includes('client')
if (broken) {
it.todo(name)
continue
}
it(name, async () => {
const browser = await next.browser(pageInfo.url)
expect(
await browser
.waitForElementByCss(pageInfo.selector)
.getComputedCss('color')
).toBe(pageInfo.color)
})
}
}
)
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -3233,6 +3233,39 @@ ...@@ -3233,6 +3233,39 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/e2e/app-dir/css-order/css-order.test.ts": {
"passed": [
"css-order should load correct styles navigating first -> first-client",
"css-order should load correct styles navigating first -> second-client",
"css-order should load correct styles navigating first -> second",
"css-order should load correct styles navigating first -> third",
"css-order should load correct styles navigating first-client -> first",
"css-order should load correct styles navigating first-client -> second-client",
"css-order should load correct styles navigating first-client -> second",
"css-order should load correct styles navigating first-client -> third",
"css-order should load correct styles navigating second -> first-client",
"css-order should load correct styles navigating second -> first",
"css-order should load correct styles navigating second -> second-client",
"css-order should load correct styles navigating second -> third",
"css-order should load correct styles navigating second-client -> first-client",
"css-order should load correct styles navigating second-client -> first",
"css-order should load correct styles navigating second-client -> second",
"css-order should load correct styles navigating second-client -> third",
"css-order should load correct styles navigating third -> first-client",
"css-order should load correct styles navigating third -> first",
"css-order should load correct styles navigating third -> second-client",
"css-order should load correct styles navigating third -> second",
"css-order should load correct styles on first-client",
"css-order should load correct styles on first",
"css-order should load correct styles on second-client",
"css-order should load correct styles on second",
"css-order should load correct styles on third"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
},
"test/e2e/app-dir/dynamic-data/dynamic-data.test.ts": { "test/e2e/app-dir/dynamic-data/dynamic-data.test.ts": {
"passed": [ "passed": [
"dynamic-data inside cache scope displays redbox when accessing dynamic data inside a cache scope", "dynamic-data inside cache scope displays redbox when accessing dynamic data inside a cache scope",
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