You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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不匹配问题

  1. 彻底清除缓存
    执行以下命令清除Next.js缓存、依赖并重新构建:

    rm -rf .next node_modules
    npm install
    npm run build
    npm run start
    

    旧缓存可能残留Babel编译逻辑,导致样式不匹配。

  2. 正确配置样式注册表(分路由模式)

    • 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>
        )
      }
      
  3. 移除自定义SWC配置
    如果项目中有.swcrc文件,直接删除,Next.js的默认SWC配置已经适配styled-components,自定义配置可能冲突。

  4. 更新styled-components版本
    执行npm install styled-components@latest,旧版本可能和Next.js 13的SWC插件存在兼容性问题。

验证解决效果

构建并启动项目后,检查页面控制台是否还存在className did not match警告。也可以查看页面元素的className,服务端渲染和客户端 hydration 生成的className应该完全一致,说明问题解决。

内容的提问来源于stack exchange,提问作者Matilda Brunemalm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:22:21