Next.js 13升级后Styled Components类名不匹配:如何迁移到SWC?
解决Next.js 13升级后styled-components的"Prop className did not match"警告(SWC方案)
先确认SWC是否正常运行
- 查看启动日志:启动项目时,控制台输出如果包含
SWC minify release candidate enabled或明确提及SWC编译的信息,说明SWC正在工作。如果出现Babel相关日志,检查是否存在残留的Babel配置文件(比如babel.config.js,不止是.babelrc),全部删除。 - 清理Babel依赖:卸载所有Babel相关包,执行
npm uninstall @babel/core babel-plugin-styled-components,避免干扰SWC运行。 - 验证配置:确保
next.config.js的SWC配置正确:/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { styledComponents: true, }, } module.exports = nextConfig
解决className不匹配问题
彻底清除缓存
执行以下命令清除Next.js缓存、依赖并重新构建:rm -rf .next node_modules npm install npm run build npm run start旧缓存可能残留Babel编译逻辑,导致样式不匹配。
正确配置样式注册表(分路由模式)
- Pages Router(pages目录):在
_app.js/_app.tsx中确保样式收集逻辑正确:import { useState } from 'react' import { StyleSheetManager, ServerStyleSheet } from 'styled-components' export default function App({ Component, pageProps }) { const [sheet] = useState(() => new ServerStyleSheet()) return ( <StyleSheetManager sheet={sheet.instance}> <Component {...pageProps} /> </StyleSheetManager> ) } - App Router(app目录):创建样式注册表组件并在根布局中引入:
新建app/registry.tsx:
然后在'use client' import { useState } from 'react' import { ServerStyleSheet, StyleSheetManager } from 'styled-components' export function StyledComponentsRegistry({ children }) { const [sheet] = useState(() => new ServerStyleSheet()) return <StyleSheetManager sheet={sheet.instance}>{children}</StyleSheetManager> }app/layout.tsx中使用:import { StyledComponentsRegistry } from './registry' export default function RootLayout({ children }) { return ( <html lang="zh-CN"> <body> <StyledComponentsRegistry>{children}</StyledComponentsRegistry> </body> </html> ) }
- Pages Router(pages目录):在
移除自定义SWC配置
如果项目中有.swcrc文件,直接删除,Next.js的默认SWC配置已经适配styled-components,自定义配置可能冲突。更新styled-components版本
执行npm install styled-components@latest,旧版本可能和Next.js 13的SWC插件存在兼容性问题。
验证解决效果
构建并启动项目后,检查页面控制台是否还存在className did not match警告。也可以查看页面元素的className,服务端渲染和客户端 hydration 生成的className应该完全一致,说明问题解决。
内容的提问来源于stack exchange,提问作者Matilda Brunemalm
相关产品推荐
相关产品推荐

