Unverified Commit fdaf35b9 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

add option to disable experimental CssChunkingPlugin (#73286)

In app router `experimental.cssChunking` is enabled by default in
"loose" mode. This is to solve issues with CSS ordering & reduce the
number of requests for CSS resources (more information can be found in
the [original PR](https://github.com/vercel/next.js/pull/63157) and the
[docs](https://nextjs.org/docs/app/api-reference/next-config-js/cssChunking)).
However, it can lead to shared CSS from unrelated pages being included
in the initially loaded CSS.

This isn't always desireable, as expressed in
https://github.com/vercel/next.js/discussions/70168. It also leads to a
drift in behavior between dev/start, as the plugin is only implemented
in start.

This provides a third option to the plugin to disable it completely for
those who are ok with the trade-offs of not having it enabled.
parent 504a52aa
...@@ -35,6 +35,7 @@ module.exports = nextConfig ...@@ -35,6 +35,7 @@ module.exports = nextConfig
- **`'loose'` (default)**: Next.js will try to merge CSS files whenever possible, determining explicit and implicit dependencies between files from import order to reduce the number of chunks and therefore the number of requests. - **`'loose'` (default)**: Next.js will try to merge CSS files whenever possible, determining explicit and implicit dependencies between files from import order to reduce the number of chunks and therefore the number of requests.
- **`'strict'`**: Next.js will load CSS files in the correct order they are imported into your files, which can lead to more chunks and requests. - **`'strict'`**: Next.js will load CSS files in the correct order they are imported into your files, which can lead to more chunks and requests.
- **`'disabled'**: Next.js will not attempt to merge or re-order your CSS files.
You may consider using `'strict'` if you run into unexpected CSS behavior. For example, if you import `a.css` and `b.css` in different files using a different `import` order (`a` before `b`, or `b` before `a`), `'loose'` will merge the files in any order and assume there are no dependencies between them. However, if `b.css` depends on `a.css`, you may want to use `'strict'` to prevent the files from being merged, and instead, load them in the order they are imported - which can result in more chunks and requests. You may consider using `'strict'` if you run into unexpected CSS behavior. For example, if you import `a.css` and `b.css` in different files using a different `import` order (`a` before `b`, or `b` before `a`), `'loose'` will merge the files in any order and assume there are no dependencies between them. However, if `b.css` depends on `a.css`, you may want to use `'strict'` to prevent the files from being merged, and instead, load them in the order they are imported - which can result in more chunks and requests.
......
...@@ -1927,6 +1927,7 @@ export default async function getBaseWebpackConfig( ...@@ -1927,6 +1927,7 @@ export default async function getBaseWebpackConfig(
}), }),
!dev && !dev &&
isClient && isClient &&
config.experimental.cssChunking !== 'disabled' &&
new CssChunkingPlugin(config.experimental.cssChunking === 'strict'), new CssChunkingPlugin(config.experimental.cssChunking === 'strict'),
!dev && !dev &&
isClient && isClient &&
......
...@@ -328,7 +328,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -328,7 +328,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
manualClientBasePath: z.boolean().optional(), manualClientBasePath: z.boolean().optional(),
middlewarePrefetch: z.enum(['strict', 'flexible']).optional(), middlewarePrefetch: z.enum(['strict', 'flexible']).optional(),
multiZoneDraftMode: z.boolean().optional(), multiZoneDraftMode: z.boolean().optional(),
cssChunking: z.enum(['strict', 'loose']).optional(), cssChunking: z.enum(['strict', 'loose', 'disabled']).optional(),
nextScriptWorkers: z.boolean().optional(), nextScriptWorkers: z.boolean().optional(),
// The critter option is unknown, use z.any() here // The critter option is unknown, use z.any() here
optimizeCss: z.union([z.boolean(), z.any()]).optional(), optimizeCss: z.union([z.boolean(), z.any()]).optional(),
......
...@@ -302,7 +302,7 @@ export interface ExperimentalConfig { ...@@ -302,7 +302,7 @@ export interface ExperimentalConfig {
* An alternative is 'strict', which will try to keep correct ordering as * An alternative is 'strict', which will try to keep correct ordering as
* much as possible, even when this leads to many requests. * much as possible, even when this leads to many requests.
*/ */
cssChunking?: 'strict' | 'loose' cssChunking?: 'strict' | 'loose' | 'disabled'
disablePostcssPresetEnv?: boolean disablePostcssPresetEnv?: boolean
cpus?: number cpus?: number
memoryBasedWorkersCount?: boolean memoryBasedWorkersCount?: boolean
...@@ -1090,6 +1090,7 @@ export const defaultConfig: NextConfig = { ...@@ -1090,6 +1090,7 @@ export const defaultConfig: NextConfig = {
remote: process.env.NEXT_REMOTE_CACHE_HANDLER_PATH, remote: process.env.NEXT_REMOTE_CACHE_HANDLER_PATH,
static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH, static: process.env.NEXT_STATIC_CACHE_HANDLER_PATH,
}, },
cssChunking: 'loose',
multiZoneDraftMode: false, multiZoneDraftMode: false,
appNavFailHandling: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE), appNavFailHandling: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE),
flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE) flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE)
......
:root {
--maxWidth: 1210px;
}
html,
body {
background: #000;
}
a {
color: aqua;
}
import type { Metadata } from 'next'
import React from 'react'
import './globals.css'
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import InnerWrapper from '../../components/inner-wrapper'
import styles from './otherPage.module.css'
export default async function OtherPage() {
return (
<InnerWrapper>
<h1 className={styles.otherPage}>Other Page Title</h1>
</InnerWrapper>
)
}
.h1 {
background: antiquewhite;
color: #1a1a1a;
}
import styles from './page.module.css'
import InnerWrapper from '../components/inner-wrapper'
import Link from 'next/link'
export default function Home() {
return (
<div className={styles.page}>
<InnerWrapper>
<h1 className={styles.h1}>Home Page</h1>
<Link href="./other" prefetch={false}>
Other page
</Link>
</InnerWrapper>
</div>
)
}
import React from 'react'
import styles from './innerWrapper.module.css'
export default function InnerWrapper({
children,
}: {
children: React.ReactNode
}) {
return <div className={styles.innerWrapper}>{children}</div>
}
.innerWrapper {
max-width: var(--maxWidth);
margin: 0 auto;
position: relative;
padding-left: 30px;
padding-right: 30px;
}
import { nextTestSetup } from 'e2e-utils'
describe('css-chunking', () => {
const { next } = nextTestSetup({ files: __dirname })
// this test asserts that all the emitted CSS files for the index page
// do not contain styles for the `/other` page, which can happen
// when the CSSChunkingPlugin is enabled and styles are shared across
// both routes.
it('should be possible to disable the chunking plugin', async () => {
const $ = await next.render$('/')
const stylesheets = $('link[rel="stylesheet"]')
stylesheets.each(async (_, element) => {
const href = element.attribs.href
const result = await next.fetch(href)
const css = await result.text()
expect(css).not.toContain('.otherPage')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
cssChunking: 'disabled',
},
}
module.exports = nextConfig
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