Skip to main content

cssChunking

CSS 分块是一种通过将 CSS 文件拆分和重新排序为块来提高 Web 应用性能的策略。这允许你仅加载特定路由所需的 CSS,而不是一次加载应用的所有 CSS。

¥CSS Chunking is a strategy used to improve the performance of your web application by splitting and re-ordering CSS files into chunks. This allows you to load only the CSS that is needed for a specific route, instead of loading all the application's CSS at once.

你可以使用 next.config.js 文件中的 experimental.cssChunking 选项控制 CSS 文件的分块方式:

¥You can control how CSS files are chunked using the experimental.cssChunking option in your next.config.js file:

import type { NextConfig } from 'next'

const nextConfig = {
experimental: {
cssChunking: 'loose', // default
},
} satisfies NextConfig

export default nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
cssChunking: 'loose', // default
},
}

module.exports = nextConfig

选项

¥Options

  • 'loose'(默认):Next.js 将尽可能尝试合并 CSS 文件,根据导入顺序确定文件之间的显式和隐式依赖,以减少块数,从而减少请求数。

    ¥**'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 将按照导入文件的正确顺序加载 CSS 文件,这会导致更多的块和请求。

    ¥**'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.

如果遇到意外的 CSS 行为,你可以考虑使用 'strict'。例如,如果你使用不同的 import 顺序(ab 之前,或 ba 之前)在不同的文件中导入 a.cssb.css'loose' 将以任何顺序合并文件并假定它们之间没有依赖。但是,如果 b.css 依赖于 a.css,你可能需要使用 'strict' 来防止文件合并,而是按照导入的顺序加载它们 - 这可能会导致更多的块和请求。

¥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.

对于大多数应用,我们推荐使用 'loose',因为它可以减少请求并提高性能。

¥For most applications, we recommend 'loose' as it leads to fewer requests and better performance.