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

使用styled-components运行Next.js项目时遇next/font与SWC、Babel冲突错误

解决Next.js中next/font与styled-components+Babel的冲突问题

你遇到的错误是因为自定义Babel配置让Next.js切换到了Babel编译,而next/font依赖SWC编译器,两者冲突导致的。以下是两种可行的解决方案:

方案一:移除Babel配置,改用SWC支持styled-components

这是推荐方案,Next.js默认使用SWC,性能更优,也能彻底解决冲突。

  1. 删除自定义Babel配置
    直接删除项目根目录的.babelrc文件,Next.js会自动切换回SWC编译流程。

  2. 修正next.config.js的styled-components配置
    你当前的next.config.js中styledComponents字段写的是类型注释而非实际配置值,需修改为有效配置对象:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  styledComponents: {
    ssr: true,
    displayName: true
  }
}
module.exports = nextConfig
  1. 保留_Document的SSR样式收集逻辑
    你的_Document文件配置是正确的,继续保留即可,确保styled-components的样式在服务端渲染时正确注入:
import Document, {
  Html,
  Head,
  Main,
  NextScript,
  DocumentContext
} from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }

  render() {
    return (
      <Html lang="pt-BR">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

方案二:保留Babel配置,替换next/font的使用方式

若你因特殊需求必须保留自定义Babel配置,需放弃next/font,改用传统字体加载方案:

  1. 添加字体文件到项目
    将字体文件(如.woff2、.ttf)放入项目public/fonts目录。

  2. 在全局CSS中定义字体
    在styles/globals.css中添加@font-face规则:

@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom-font.woff2') format('woff2');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}
  1. 导入全局CSS到_app
    在_app.tsx中确保全局CSS被正确导入:
import '../styles/globals.css'
import type { AppProps } from 'next/app'

export default function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
  1. 在styled-components中使用字体
    之后即可在styled-components中直接引用定义好的字体:
import styled from 'styled-components'

const StyledParagraph = styled.p`
  font-family: 'CustomFont', sans-serif;
`

内容的提问来源于stack exchange,提问作者Yuri Oliveira Gochi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:55:33