Next.js13 SSR模式下使用styled-components的报错解决方案
Next.js 13中使用styled-components的SSR解决方案
错误现象
使用styled-components时触发以下服务器错误:
Server Error
TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
替换为原生HTML标签(如main)则可正常运行。
问题代码示例
Hero组件
import Link from "next/link"; import StyledHero from "../Hero.style"; const Hero = () => { return ( <StyledHero> <h1>Stowarzyszenie Juz Lepiej</h1> <h2>Przybywam w celu:</h2> <Link about="Panel wolontariusza" href="/volunteer">Uzyskania pomocy</Link> <Link about="Panel podopiecznego" href="/mentee">Niesienia pomocy</Link> </StyledHero> ) }; export default Hero;
Hero.style.ts样式文件
import styled from "styled-components"; const StyledHero = styled.main` width: 100%; height: auto; padding: 10em; ` export default StyledHero;
已配置的.babelrc
{ "presets": [ "next/babel" ], "plugins": [ [ "styled-components", { "ssr": true, "displayName": true, "preprocess": false } ] ] }
package.json依赖
{ "name": "mentalhealthcharity", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@next/font": "13.2.4", "@types/node": "18.15.11", "@types/react": "18.0.31", "@types/react-dom": "18.0.11", "@types/styled-components": "^5.1.26", "eslint": "8.37.0", "eslint-config-next": "13.2.4", "next": "13.2.4", "react": "18.2.0", "react-dom": "18.2.0", "styled-components": "^5.3.9", "typescript": "5.0.2", "zustand": "^4.3.6" }, "devDependencies": { "babel-plugin-styled-components": "^2.0.7" } }
可行解决方案
1. 给组件添加"use client"指令
Next.js 13 App Router默认所有组件为服务器组件,而styled-components依赖React Context(createContext),只能在客户端组件中运行。需在使用styled-components的组件文件顶部添加指令:
"use client"; // 新增该行 import Link from "next/link"; import StyledHero from "../Hero.style"; const Hero = () => { // 组件内容不变 }; export default Hero;
2. 改用Next.js官方推荐的编译器配置(替代.babelrc)
对于App Router,Next.js推荐通过next.config.js配置styled-components,避免babel配置冲突:
/** @type {import('next').NextConfig} */ const nextConfig = { compiler: { styledComponents: true, }, } module.exports = nextConfig;
该配置会自动处理SSR样式注入、生成displayName等需求,无需额外配置babel插件。
3. 验证与缓存清理
- 启动项目后查看页面源码,若能看到带有
data-styled属性的样式标签,说明SSR配置生效。 - 若仍有问题,清除Next.js缓存后重新启动:
rm -rf .next npm run dev
内容的提问来源于stack exchange,提问作者Jakub Łobos
相关产品推荐
相关产品推荐

