引言:Next.js 样式方案的重要性
在现代 React 开发中,样式管理是构建高质量 Web 应用的关键环节。Next.js 作为 React 生态中最流行的全栈框架,提供了多种灵活的样式解决方案。无论是传统的全局 CSS、CSS Modules,还是现代化的 CSS-in-JS 库,Next.js 都能完美支持。然而,如何在项目中正确配置、使用并优化这些方案,是每个 Next.js 开发者必须掌握的核心技能。
本文将深入探讨 Next.js 中的全局样式与 CSS-in-JS 实战,从基础配置到高级优化,帮助你构建既美观又高性能的 Next.js 应用。
一、Next.js 全局样式配置与最佳实践
1.1 全局 CSS 的基本配置
Next.js 支持开箱即用的全局 CSS。你只需要在
pages/_app.js
(或
pages/_app.tsx
)中导入 CSS 文件即可。
步骤 1:创建全局样式文件
在项目根目录下创建
styles/globals.css
文件:
/* styles/globals.css */
:root {
–primary-color: #0070f3;
–secondary-color: #e0e0e0;
–font-family: -apple-system, BlinkMacSystemFont, ‘Segoe UI’, ‘Roboto’, ‘Oxygen’,
‘Ubuntu’, ‘Cantarell’, ‘Fira Sans’, ‘Droid Sans’, ‘Helvetica Neue’,
sans-serif;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: var(–font-family);
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}
a {
color: var(–primary-color);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
步骤 2:在
_app.js
中导入
// pages/_app.js
import ‘../styles/globals.css’;
function MyApp({ Component, pageProps }) {
return
}
export default MyApp;
关键点说明
:
_app.js
是 Next.js 的自定义应用组件,所有页面都会通过它渲染
全局 CSS 只能在
_app.js
中导入,其他页面文件中导入全局 CSS 会导致构建错误
CSS 变量(Custom Properties)是现代浏览器支持的强大功能,推荐用于主题切换
1.2 全局样式的高级用法
使用 CSS Modules 实现局部作用域
虽然我们讨论的是全局样式,但 Next.js 也内置支持 CSS Modules,这是避免样式冲突的最佳实践:
/* components/Button.module.css */
.button {
padding: 10px 20px;
background-color: var(–primary-color);
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
.button:hover {
background-color: #005bb5;
}
.button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
// components/Button.js
import styles from ‘./Button.module.css’;
export default function Button({ children, disabled = false }) {
return (
);
}
预处理器支持(Sass/Less/Stylus)
Next.js 内置支持 Sass,只需安装依赖即可:
npm install sass
# 或
yarn add sass
然后创建
.scss
文件:
// styles/variables.scss
$primary-color: #0070f3;
$breakpoint-mobile: 768px;
// styles/layout.scss
@import ‘./variables’;
.header {
background-color: $primary-color;
padding: 1rem 0;
@media (max-width: $breakpoint-mobile) {
padding: 0.5rem 0;
}
}
1.3 全局样式优化策略
1.3.1 CSS 代码分割
虽然全局 CSS 会在所有页面加载,但你可以通过动态导入来优化:
// pages/_app.js
import { useEffect } from ‘react’;
import ‘../styles/globals.css’;
function MyApp({ Component, pageProps }) {
// 根据页面动态加载额外的 CSS
useEffect(() => {
// 这里可以添加条件逻辑,按需加载特定页面的 CSS
if (window.location.pathname.startsWith(‘/dashboard’)) {
import(‘../styles/dashboard.css’);
}
}, []);
return
}
export default MyApp;
1.3.2 使用 CSS 变量实现主题切换
/* styles/globals.css */
:root {
–bg-color: #ffffff;
–text-color: #333333;
–border-color: #e0e0e0;
}
[data-theme=”dark”] {
–bg-color: #1a1a1a;
–text-color: #f0f0f0;
–border-color: #444444;
}
body {
background-color: var(–bg-color);
color: var(–text-color);
}
// components/ThemeToggle.js
import { useEffect, useState } from ‘react’;
export default function ThemeToggle() {
const [theme, setTheme] = useState(‘light’);
useEffect(() => {
const savedTheme = localStorage.getItem(‘theme’) || ‘light’;
setTheme(savedTheme);
document.documentElement.setAttribute(‘data-theme’, savedTheme);
}, []);
const toggleTheme = () => {
const newTheme = theme === ‘light’ ? ‘dark’ : ‘light’;
setTheme(newTheme);
document.documentElement.setAttribute(‘data-theme’, newTheme);
localStorage.setItem(‘theme’, newTheme);
};
return (
);
}
二、CSS-in-JS 在 Next.js 中的配置与实战
2.1 主流 CSS-in-JS 库对比
库名称
优点
缺点
Next.js 支持度
styled-components
社区庞大、功能完善、支持主题
运行时开销
官方推荐
Emotion
性能优秀、API 简洁
生态稍小
良好支持
Linaria
零运行时开销
配置复杂
需要额外配置
JSS
灵活、可扩展
学习曲线陡峭
良好支持
2.2 styled-components 实战配置
步骤 1:安装依赖
npm install styled-components babel-plugin-styled-components
# 或
yarn add styled-components babel-plugin-styled-components
步骤 2:配置 Babel(可选但推荐)
在
.babelrc
或
babel.config.js
中:
// babel.config.js
module.exports = {
presets: [
‘next/babel’,
],
plugins: [
[
‘babel-plugin-styled-components’,
{
ssr: true,
displayName: true,
preprocess: false,
},
],
],
};
步骤 3:创建 Styled Components
// components/Card.js
import styled from ‘styled-components’;
const CardWrapper = styled.div`
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.2s, box-shadow 0.2s;
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
${props => props.primary && `
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
`}
`;
const CardTitle = styled.h3`
font-size: 1.5rem;
margin-bottom: 10px;
font-weight: 600;
`;
const CardContent = styled.p`
color: ${props => props.primary ? ‘rgba(255,255,255,0.9)’ : ‘#666’};
line-height: 1.6;
`;
export default function Card({ title, content, primary = false }) {
return (
);
}
步骤 4:使用主题系统
// pages/_app.js
import { ThemeProvider } from ‘styled-components’;
import ‘../styles/globals.css’;
const theme = {
colors: {
primary: ‘#0070f3’,
secondary: ‘#e0e0e0’,
success: ‘#28a745’,
danger: ‘#dc3545’,
},
fonts: {
body: ‘system-ui, -apple-system, sans-serif’,
heading: ‘Georgia, serif’,
},
spacing: {
small: ‘8px’,
medium: ’16px’,
large: ’24px’,
},
};
function MyApp({ Component, pageProps }) {
return (
);
}
export default MyApp;
// components/ThemedButton.js
import styled from ‘styled-components’;
const ThemedButton = styled.button`
background-color: ${props => props.theme.colors.primary};
color: white;
padding: ${props => props.theme.spacing.medium} ${props => props.theme.spacing.large};
border: none;
border-radius: 4px;
font-family: ${props => props.theme.fonts.body};
cursor: pointer;
transition: opacity 0.2s;
&:hover {
opacity: 0.8;
}
&:disabled {
background-color: #ccc;
cursor: not-allowed;
}
`;
export default ThemedButton;
2.3 Emotion 实战配置
安装与配置
npm install @emotion/react @emotion/styled
// .babelrc
{
“presets”: [“next/babel”],
“plugins”: [“@emotion/babel-plugin”]
}
Emotion 使用示例
// components/EmotionCard.js
/** @jsxImportSource @emotion/react */
import { css } from ‘@emotion/react’;
import styled from ‘@emotion/styled’;
const cardStyle = css`
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
&:hover {
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
`;
const CardWrapper = styled.div`
${cardStyle}
${props => props.primary && `
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
`}
`;
const CardTitle = styled.h3`
font-size: 1.5rem;
margin-bottom: 10px;
font-weight: 600;
${props => props.primary && `color: white;`}
`;
export default function EmotionCard({ title, children, primary = false }) {
return (
{children}
);
}
2.4 CSS-in-JS 性能优化策略
2.4.1 使用
babel-plugin-styled-components
的 SSR 优化
确保在服务器端渲染时,样式能够正确注入到 HTML 中,避免闪烁:
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from ‘next/document’;
import { ServerStyleSheet } from ‘styled-components’;
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(
});
const initialProps = await Document.getInitialProps(ctx);
return {
…initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
>),
};
} finally {
sheet.seal();
}
}
render() {
return (