Hur jag eliminerade 94 renderingsblockerande CSS-filer i Next.js 16 med en dåligt dokumenterad Turbopack-funktion
Efter dagar av att prova varje tillvägagångssätt — från experimental.inlineCss till MutationObserver-hack — upptäckte jag Turbopack Import Attributes som löser problemet med renderingsblockerande CSS i Next.js App Router.
Problemet
Vår app (Promova) använder Next.js 16 med en Landing Builder — ett CMS-drivet system som sätter ihop marknadsföringssidor från ~90 olika sektionskomponenter. Arkitekturen använder en sectionRegistry.tsx som mappar sektionsnamn till next/dynamic()-anrop:
// sectionRegistry.tsx — imports all 90 sections
export const sectionRegistry = {
HeroSection: dynamic(() => import('./HeroSection/HeroSection')),
FAQSection: dynamic(() => import('./FAQSection/FAQSection')),
ReviewsSection: dynamic(() => import('./ReviewsSection/ReviewsSection')),
// ... 87 more
}En enda landningssida renderar bara 5-8 sektioner. Men Lighthouse visade:
Eliminate render-blocking resources
94 CSS resources (~330 KB)
Potential savings: 5,440 msVarför? Turbopack ser alla 90 import()-sökvägar som nåbara och genererar <link rel="stylesheet"> för varje SCSS-modul. Även sektioner som aldrig renderas på sidan får sin CSS injicerad i <head>. Detta är ett bekräftat, förväntat beteende i Next.js App Router. Ingen fix planeras.
Allt jag försökte (och varför det misslyckades)
Jag spenderade dagar på att gå igenom varje tillvägagångssätt jag kunde hitta. Här är hela listan:
| Approach | Why it doesn't work |
|---|---|
Split sectionRegistry into per-section files | CSS still loaded — #61066 |
experimental.inlineCss: true | Inlines CSS on every SSR request — crashed our CMS under load |
experimental.optimizeCss (Critters) | Incompatible with streaming in App Router |
| CSS-in-JS rewrite | Rewriting 90 sections from SCSS to CSS-in-JS is not realistic |
media="print" hack | Doesn't work with CSS Modules in Turbopack — <link> tags are managed by the framework |
| Switch back to Webpack | Has experiments.css options, but we're committed to Turbopack |
| Turbopack plugins | Don't exist — no plugin API |
| Turbopack CSS loaders | Not supported — only JS output |
| SWC plugins for CSS | SWC only processes JavaScript |
Client Component wrapper for dynamic() | Registry is a global constant — bundler sees all dependencies |
| Next.js middleware HTML rewrite | Middleware can't modify response body |
| Suspense + streaming with async import | React Float always pulls CSS into initial <head> |
| Suspense + 3s delay | Content streams later, but CSS is in the initial <head> chunk |
experimental.cssChunking | Already default. Merges chunks but doesn't remove irrelevant CSS |
| Post-build Beasties/Critters | Only for static export, not with ISR |
| npm libraries (next-critical, fg-loadcss) | Pages Router only or abandoned (6+ years) |
inlineCss per-route exclusion | Not supported — all-or-nothing global flag |
Turbopack as: 'raw' for SCSS | Returns undefined instead of text |
Turbopack rule for *.inline.module.scss | Turbopack intercepts .module.scss before custom rules |
Turbopack rule for *.inline.scss | Turbopack intercepts .scss before custom rules |
MutationObserver <script> | Tested in dev, risky — CSS still loads as separate files, possible FOUC |
inlineCss-fällan
Next.js har en experimental.inlineCss-flagga som ersätter alla <link rel="stylesheet"> med inline <style>-taggar. Låter perfekt, eller hur?
Problemet: det är allt eller inget. Du kan inte aktivera det per rutt. Om du har SSR-sidor (force-dynamic) bygger varje begäran om all CSS inline. Vi försökte — vår headless CMS klarade inte lasten.
Upptäckten: Turbopack Import Attributes
Genom att gräva i Next.js 16.2-releasenotes hittade jag en dåligt dokumenterad funktion: Turbopack Import Attributes. Den låter dig åsidosätta den inbyggda bundler-pipelinen för en specifik import med TC39 with {}-syntax:
import { cssText, styles } from './hero.module.scss' with {
turbopackLoader: '@promova/scss-to-inline-loader',
turbopackAs: '*.js'
}Detta säger till Turbopack: "Bearbeta inte denna import som en stilmall. Kör den genom min anpassade loader och behandla utdatan som JavaScript."
Detta är den avgörande insikten. Istället för att Turbopack genererar ett <link rel="stylesheet"> som blockerar rendering, kompilerar vår loader SCSS och exporterar det som en JS-sträng. Resultat: bara CSS för sektioner som faktiskt renderas hamnar i sidans HTML.
Lösningen
1. Anpassad Turbopack Loader
Ett ~70-radigt Node.js-skript som yarn workspace-paket (@promova/scss-to-inline-loader):
const { createHash } = require('node:crypto')
const sass = require('sass')
const postcss = require('postcss')
const postcssModules = require('postcss-modules')
const path = require('path')
const SHARED_STYLES = path.resolve(__dirname, '../shared/styles')
// Same prependData as sassOptions.prependData in next.config.ts
const PREPEND_DATA = `
@use "sass:math" as math;
@use "sass:list" as list;
@use "${SHARED_STYLES}/_variables.scss" as *;
@use "${SHARED_STYLES}/_breakpoints.scss" as *;
@use "${SHARED_STYLES}/_mixins.scss" as *;
`
module.exports = function scssToInlineLoader(source) {
const callback = this.async()
processScss(source, this.resourcePath)
.then((js) => callback(null, js))
.catch((err) => callback(err))
}
async function processScss(source, resourcePath) {
// 1. Compile SCSS → CSS (with global variables, mixins, breakpoints)
const sassResult = sass.compileString(PREPEND_DATA + '\n' + source, {
loadPaths: [path.dirname(resourcePath), SHARED_STYLES],
style: 'compressed',
sourceMap: false,
url: new URL('file://' + resourcePath),
})
// 2. Scope class names with postcss-modules (CSS Modules compatible)
let classNames = {}
const result = await postcss([
postcssModules({
generateScopedName(name, filename) {
const file = path.basename(filename, path.extname(filename))
.replace('.module', '')
const hash = createHash('md5')
.update(filename + name)
.digest('base64url')
.slice(0, 6)
return `${file}__${name}__${hash}`
},
getJSON(_, json) { classNames = json },
}),
]).process(sassResult.css, { from: resourcePath })
// 3. Export as JS module — same interface as CSS Modules
return [
`export const cssText = ${JSON.stringify(result.css)};`,
`export const styles = ${JSON.stringify(classNames)};`,
`export default styles;`,
].join('\n')
}Vad den gör: styles — samma scopade klassnamnskarta som standard CSS Modules. cssText — kompilerad CSS som sträng.
2. InlineStyle-komponent
Använder React 19s inbyggda <style href precedence>-API för automatisk deduplicering:
export function InlineStyle({ css, id }: { css: string; id: string }) {
return (
<style href={id} precedence="default">
{css}
</style>
)
}React 19 garanterar: samma href → bara en <style> i DOM.
3. Migration per komponent (~6 rader per sektion)
// BEFORE: Turbopack → <link rel="stylesheet"> (render-blocking)
import styles from './hero_section.module.scss'// AFTER: Custom loader → JS module → inline <style> (non-blocking)
import { cssText, styles } from './hero_section.module.scss' with {
turbopackLoader: '@promova/scss-to-inline-loader',
turbopackAs: '*.js'
}
import { InlineStyle } from '@promova/scss-to-inline-loader/InlineStyle'
export function HeroSection() {
return (
<section className={styles.hero}>
<InlineStyle css={cssText} id="hero-section" />
{/* ... component JSX, className usage is identical */}
</section>
)
}.module.scss-filerna förblir exakt desamma. Ingen CSS-omskrivning.
Varför detta är bättre än inlineCss: true
Här är den kritiska skillnaden:
| <code>inlineCss: true</code> | Import Attributes + Loader | |
|---|---|---|
| What gets inlined | ALL CSS on the page (94 files) | Only CSS for rendered sections (5-8 files) |
| SSR overhead | CSS rebuilt on every request | CSS compiled at build time |
| Per-route control | No (all-or-nothing) | Yes (per-import) |
| SSR pages safety | Risky (overloads server) | Safe (component-level) |
Med inlineCss: true får en sida fortfarande ALLA 94 stilmallar inline. Med vår metod hamnar bara CSS som faktiskt renderas i HTML:en.
Turbopack-fällan: inga globala regler för .module.scss
En fälla jag föll i: du kanske tror att du kan lägga till en Turbopack-regel i next.config.ts för att tillämpa loadern globalt:
// ❌ THIS CAUSES A FATAL PANIC
turbopack: {
rules: {
'**/components/**/*.module.scss': {
loaders: ['@promova/scss-to-inline-loader'],
as: '*.js'
}
}
}Gör inte detta. Turbopacks inbyggda CSS-module-pipeline fångar .module.scss-filer innan anpassade regler tillämpas, vilket orsakar:
FATAL PANIC: inner asset should be CSS processablewith {}-attribut fungerar eftersom de instruerar Turbopack vid import-platsen att helt kringgå CSS-module-pipelinen.
Resultat
127 sektionskomponenter migrerade i Landing Builder. Produktionsbygge verifierat.
| Metric | Before | After |
|---|---|---|
| Render-blocking CSS files | 94 | 0 (for landing sections) |
| CSS in HTML per page | ~330 KB (all sections) | ~20-40 KB (rendered sections only) |
| CSS delivery | <link> (network request, blocking) | <style> (inline, non-blocking) |
| Sass features | Full | Full (variables, mixins, nesting, @use) |
| CSS Modules scoping | Built-in | postcss-modules (compatible) |
| Code change per section | — | ~6 lines (import + InlineStyle) |
Begränsningar
with {}per import är mångsidigt — varje import behöver 3 extra rader.- Bara Turbopack —
with {}-attribut stöds inte av Webpack. - Klassnamns-hashning — vår loader använder en annan hashningsalgoritm än Turbopacks inbyggda.
- HTML-storlek ökar — CSS är inline i HTML istället för cachade separata filer.
När man ska använda detta
Denna teknik är mest effektiv när:
- Du har ett registry/barrel-mönster — en fil importerar många komponenter, men bara några få renderas per sida
- Du använder Turbopack — Import Attributes är Turbopack-specifika
- Du vill ha kontroll per komponent — inte en allt-eller-inget-flagga
- Din SCSS är komplex — variabler, mixins, breakpoints, nästling — allt stöds
- Du inte kan använda
experimental.inlineCss— för att du har SSR-sidor eller vill ha granulär kontroll
Relaterade GitHub Issues
Om du påverkas av renderingsblockerande CSS i Next.js App Router — du är inte ensam:
Kärnproblemet
- #62485 — Render blocking CSS (maintainers: "expected behavior")
- #61066 — Dynamic imports from Server Components are not code-split
- #54935 — Server-side dynamic imports don't split client modules
- #61574 — JS/CSS code splitting doesn't work as documented
- #57634 — Add support for critical CSS inlining with App Router
- #50300 — next/dynamic on server component does not build CSS modules
inlineCss-funktionen & problem
- PR #72195 — experimental: css inlining (the implementation)
- PR #73182 — Don't inline CSS in RSC payload for client navigation
- #75648 — WhatsApp preview broken with inlineCss + Tailwind
- #83612 — Turbopack wrong font URL with inline CSS
Communityn söker lösningar
- Discussion #82894 — How to prevent render-blocking with CSS Modules? (2025)
- Discussion #70526 — Ideas for reducing render-blocking CSS
- Discussion #59814 — Render blocking styles with Tailwind
- Discussion #49691 — How to deal with render-blocking modular CSS
- Discussion #59989 — Critical CSS inlining with App Router
- Discussion #80486 — Is optimizeCss still in use?
- Discussion #85465 — Turbopack plugin API (doesn't exist)
Turbopack CSS-buggar
- #68412 — Incorrect CSS modules load order with external components
- #76464 — Turbopack sometimes strips SCSS imports
- #82497 — SCSS module not loading when not-found.tsx is present
- #88544 — Exporting Sass variables from CSS modules doesn't work with Turbopack
Byggt på Promova — en språkinlärningsplattform som betjänar miljontals användare.