安装与配置 #

一、安装 Styled Components #

1.1 使用 npm 安装 #

bash
npm install styled-components

1.2 使用 yarn 安装 #

bash
yarn add styled-components

1.3 使用 pnpm 安装 #

bash
pnpm add styled-components

二、基础项目配置 #

2.1 Create React App #

bash
npx create-react-app my-app
cd my-app
npm install styled-components

直接使用,无需额外配置:

jsx
import styled from 'styled-components';

const Title = styled.h1`
  color: blue;
`;

function App() {
  return <Title>Hello World</Title>;
}

export default App;

2.2 Vite 项目 #

bash
npm create vite@latest my-app -- --template react
cd my-app
npm install styled-components

Vite 配置(可选优化):

javascript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [
          [
            'babel-plugin-styled-components',
            {
              displayName: true,
              ssr: false,
            },
          ],
        ],
      },
    }),
  ],
});

2.3 Next.js 项目 #

bash
npx create-next-app@latest my-app
cd my-app
npm install styled-components

Next.js 需要配置 SSR 支持:

javascript
const nextConfig = {
  compiler: {
    styledComponents: true,
  },
};

module.exports = nextConfig;

创建注册文件 lib/registry.tsx

tsx
'use client';

import React, { useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';

export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode;
}) {
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet());

  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement();
    styledComponentsStyleSheet.instance.clearTag();
    return <>{styles}</>;
  });

  if (typeof window !== 'undefined') {
    return <>{children}</>;
  }

  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  );
}

app/layout.tsx 中使用:

tsx
import StyledComponentsRegistry from './lib/registry';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>
          {children}
        </StyledComponentsRegistry>
      </body>
    </html>
  );
}

三、Babel 插件配置 #

3.1 为什么需要 Babel 插件 #

text
无插件时
├── 类名不友好: sc-aXZVg
├── 无源码映射
└── 调试困难

有插件后
├── 类名清晰: Button__Button-sc-aXZVg
├── 支持源码映射
└── 更好的调试体验

3.2 安装 Babel 插件 #

bash
npm install --save-dev babel-plugin-styled-components

3.3 配置 .babelrc #

json
{
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "displayName": true,
        "preprocess": true,
        "minify": true,
        "transpileTemplateLiterals": true,
        "ssr": true,
        "pure": true
      }
    ]
  ]
}

3.4 插件选项说明 #

选项 默认值 说明
displayName true 添加组件名到类名
ssr true 启用 SSR 支持
preprocess false 预处理样式
minify false 压缩样式
transpileTemplateLiterals true 转译模板字面量
pure false 标记为纯函数

3.5 开发与生产配置 #

json
{
  "env": {
    "development": {
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "displayName": true,
            "ssr": false
          }
        ]
      ]
    },
    "production": {
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "displayName": false,
            "minify": true,
            "pure": true
          }
        ]
      ]
    }
  }
}

四、TypeScript 配置 #

4.1 安装类型定义 #

bash
npm install --save-dev @types/styled-components

4.2 基础类型使用 #

tsx
import styled from 'styled-components';

interface ButtonProps {
  primary?: boolean;
  size?: 'small' | 'medium' | 'large';
}

const Button = styled.button<ButtonProps>`
  padding: ${props => 
    props.size === 'small' ? '8px 16px' :
    props.size === 'large' ? '16px 32px' :
    '12px 24px'
  };
  background: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
`;

function App() {
  return (
    <>
      <Button primary>Primary</Button>
      <Button size="large">Large</Button>
    </>
  );
}

4.3 扩展主题类型 #

创建 styled.d.ts

typescript
import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
    colors: {
      primary: string;
      secondary: string;
      background: string;
      text: string;
    };
    fonts: {
      main: string;
      code: string;
    };
    spacing: {
      small: string;
      medium: string;
      large: string;
    };
  }
}

定义主题:

typescript
import { DefaultTheme } from 'styled-components';

export const lightTheme: DefaultTheme = {
  colors: {
    primary: '#007bff',
    secondary: '#6c757d',
    background: '#ffffff',
    text: '#333333',
  },
  fonts: {
    main: 'Inter, sans-serif',
    code: 'Fira Code, monospace',
  },
  spacing: {
    small: '8px',
    medium: '16px',
    large: '24px',
  },
};

export const darkTheme: DefaultTheme = {
  colors: {
    primary: '#4da3ff',
    secondary: '#9ca3af',
    background: '#1a1a1a',
    text: '#e5e5e5',
  },
  fonts: {
    main: 'Inter, sans-serif',
    code: 'Fira Code, monospace',
  },
  spacing: {
    small: '8px',
    medium: '16px',
    large: '24px',
  },
};

五、ESLint 配置 #

5.1 安装 ESLint 插件 #

bash
npm install --save-dev eslint-plugin-styled-components-a11y

5.2 配置 .eslintrc #

json
{
  "plugins": ["styled-components-a11y"],
  "rules": {
    "styled-components-a11y/alt-text": "error",
    "styled-components-a11y/click-events-have-key-events": "warn"
  }
}

六、VS Code 配置 #

6.1 安装插件 #

推荐安装以下 VS Code 插件:

  • vscode-styled-components - 语法高亮和智能提示

6.2 settings.json 配置 #

json
{
  "editor.syntaxHighlight": true,
  "editor.quickSuggestions": {
    "strings": true
  },
  "css.validate": false,
  "styled-components.tags": [
    "styled",
    "css",
    "createGlobalStyle",
    "keyframes"
  ]
}

6.3 语法高亮效果 #

jsx
const Button = styled.button`
  /* 这里会有完整的 CSS 语法高亮 */
  padding: 10px 20px;
  background: ${props => props.primary ? 'blue' : 'gray'};
  
  &:hover {
    opacity: 0.8;
  }
`;

七、项目结构建议 #

7.1 组件内联样式 #

text
src/
├── components/
│   ├── Button/
│   │   ├── index.tsx        # 组件逻辑 + 样式
│   │   └── types.ts         # 类型定义
│   └── Card/
│       └── index.tsx
└── App.tsx

7.2 样式文件分离 #

text
src/
├── components/
│   ├── Button/
│   │   ├── index.tsx        # 组件逻辑
│   │   └── styles.ts        # 样式定义
│   └── Card/
│       ├── index.tsx
│       └── styles.ts
├── styles/
│   ├── theme.ts             # 主题配置
│   ├── GlobalStyle.ts       # 全局样式
│   └── mixins.ts            # 样式复用
└── App.tsx

7.3 样式文件示例 #

styles.ts

typescript
import styled from 'styled-components';

export const StyledButton = styled.button`
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.2s;
  
  &:hover {
    transform: translateY(-2px);
  }
`;

export const StyledCard = styled.div`
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
`;

index.tsx

tsx
import { StyledButton } from './styles';

interface ButtonProps {
  children: React.ReactNode;
  onClick?: () => void;
}

export function Button({ children, onClick }: ButtonProps) {
  return (
    <StyledButton onClick={onClick}>
      {children}
    </StyledButton>
  );
}

八、常见问题 #

8.1 类名闪烁问题 #

问题:页面加载时出现样式闪烁

解决方案:

jsx
import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  *, *::before, *::after {
    box-sizing: border-box;
  }
  
  body {
    margin: 0;
    font-family: system-ui, sans-serif;
  }
`;

function App() {
  return (
    <>
      <GlobalStyle />
      <YourApp />
    </>
  );
}

8.2 SSR 样式丢失 #

确保正确配置 SSR:

jsx
import { renderToString } from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';

function renderApp() {
  const sheet = new ServerStyleSheet();
  
  try {
    const html = renderToString(
      sheet.collectStyles(<App />)
    );
    const styleTags = sheet.getStyleTags();
    
    return `
      <!DOCTYPE html>
      <html>
        <head>
          ${styleTags}
        </head>
        <body>
          <div id="root">${html}</div>
        </body>
      </html>
    `;
  } finally {
    sheet.seal();
  }
}

8.3 开发环境警告 #

抑制开发环境的警告:

javascript
const originalConsoleError = console.error;
console.error = (...args) => {
  if (
    typeof args[0] === 'string' &&
    args[0].includes('component has been created dynamically')
  ) {
    return;
  }
  originalConsoleError(...args);
};

九、版本兼容性 #

9.1 React 版本要求 #

Styled Components React 版本
v6.x React 18+
v5.x React 16.8+
v4.x React 16.3+

9.2 浏览器支持 #

text
支持的浏览器
├── Chrome 60+
├── Firefox 55+
├── Safari 12+
├── Edge 79+
└── Node.js 12+

十、总结 #

配置要点:

配置项 说明
安装 npm install styled-components
Babel 插件 开发调试必需
TypeScript 安装 @types/styled-components
VS Code 安装语法高亮插件
SSR 配置 ServerStyleSheet

推荐配置流程:

  1. 安装核心依赖
  2. 配置 Babel 插件
  3. 配置 TypeScript 类型
  4. 安装 VS Code 插件
  5. 设置项目结构
最后更新:2026-03-28