Communitygithub.com

暗色模式

使用CSS变量实现主题切换,支持系统偏好检测、next-themes库以及持久化存储。

暗色模式 是什么?

此技能面向Next.js开发者,提供一套完整的暗色模式实现方案。它基于`next-themes`库,通过在应用外层包裹`<ThemeProvider>`并设置`attribute="class"`和`defaultTheme="system"`,实现对用户操作系统主题偏好的自动检测与响应。技能详细指导了如何利用CSS变量在`:root`和`.dark`伪类中定义明暗主题的色板,并通过`var(--)`方式引用,确保主题切换的灵活性与可维护性。同时,它提供了主题切换组件的示例代码,该组件使用`useTheme`钩子读取当前主题状态并实现切换,并通过状态变量`mounted`确保组件在客户端挂载后再渲染,以避免水合错误。此外,还涵盖了Tailwind CSS的集成方法、通过`localStorage`实现持久化的原理,以及添加`transition-colors`实现平滑过渡动画等关键实践。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/YepAPI/skills/tree/HEAD/skills/dark-mode

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

暗色模式 是做什么的?

规则

  • 在 Next.js 应用中使用 next-themes — 将应用包裹在 <ThemeProvider attribute="class" defaultTheme="system"> 中
  • 使用 CSS 变量定义颜色 — 在 :root (亮色) 和 .dark (暗色) 中定义,通过 var(--background) 引用
  • 系统偏好检测:defaultTheme="system" 会尊重 prefers-color-scheme 媒体查询
  • 主题切换组件:在 light/dark/system 之间循环 — 使用来自 next-themes 的 useTheme() 钩子
  • Tailwind 集成:在 tailwind 配置中启用 darkMode: "class",使用 dark: 前缀进行覆盖
  • 水合修复:通过仅在 useEffect 之后挂载主题切换组件,或使用 suppressHydrationWarning 来抑制水合不匹配
  • 持久化:next-themes 将偏好存储在 localStorage 中,并作为 class 应用于 <html> 元素
  • 过渡效果:在 body 上添加 transition-colors duration-200 以实现平滑的主题切换

模式

// 布局包裹器
import { ThemeProvider } from "next-themes";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body>
        <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}
// 主题切换组件
"use client";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";

export function ThemeToggle() {
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  if (!mounted) return null;

  return (
    <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
      {theme === "dark" ? "☀️" : "🌙"}
    </button>
  );
}
/* CSS 变量 */
:root {
  --background: 0 0% 100%;
  --foreground: 222.2 84% 4.9%;
}
.dark {
  --background: 222.2 84% 4.9%;
  --foreground: 210 40% 98%;
}

避免

  • 硬编码颜色而非使用 CSS 变量 — 会导致无法实现主题切换
  • 忘记在 <html> 上使用 suppressHydrationWarning — 会导致水合错误
  • 错误主题闪烁:确保 next-themes 脚本在绘制前运行(默认情况下它会这样做)
  • 仅支持亮色/暗色而不提供系统选项 — 应尊重用户的操作系统偏好

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

YepAPI/skills

WCAG 2.1 AA — semantic HTML, keyboard navigation, screen readers.

YepAPI/skills

Experiment setup, variant splitting, statistical significance, and feature flag integration.

YepAPI/skills

CRUD generators, data tables, user management, role-based access, and bulk operations.

YepAPI/skills

Monitor what ChatGPT and Gemini say about your brand using YepAPI.

YepAPI/skills

Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

YepAPI/skills

Commander.js, interactive prompts with Clack, spinners, colors, config files, exit codes, and npm publishing.

YepAPI/skills

cmdk integration, Cmd+K trigger, fuzzy search, grouped actions, keyboard navigation, and dynamic action registration.

YepAPI/skills

Content planning with trend and sentiment data from YepAPI.

YepAPI/skills

Content calendar, keyword-driven planning, and content briefs.

YepAPI/skills

Threaded comments, @mentions, reactions, moderation queue, optimistic UI, and cursor pagination.

YepAPI/skills

Competitive analysis between domains using YepAPI.

YepAPI/skills

Layout grids, KPI cards, data tables with sorting/filtering, sidebar navigation, and responsive breakpoints.

YepAPI/skills

Data encryption — TLS everywhere, AES-256-GCM for PII, bcrypt passwords, encrypted backups.

YepAPI/skills

Chart patterns with Recharts/Nivo/D3, responsive containers, color scales, and accessibility.

YepAPI/skills

Drizzle schema definition, push vs migrate, type-safe queries, relations, transactions, and prepared statements.

YepAPI/skills

Upload handling, resize/compress, CDN delivery, blur placeholders, and next/image patterns.

YepAPI/skills

Local business and Google Maps research using YepAPI.

YepAPI/skills

Cursor-based pagination, IntersectionObserver, virtualized lists with @tanstack/react-virtual, and scroll position restoration.

YepAPI/skills

Tenant isolation (row-level vs schema), subdomain routing, per-tenant config, and data partitioning.

YepAPI/skills

Chat UI components, streaming responses with AI SDK, context window management, and RAG patterns.

相关技能