Indicación para agregar modo oscuro con Tailwind CSS v4
Indicación para agente de IA para agregar modo oscuro consciente del sistema a una aplicación Next.js usando variables CSS de Tailwind CSS v4 y next-themes, sin destello al cargar.
CursorClaude CodeCodexWindsurf Next.jsTypeScriptTailwind
Entrega esta indicación a tu agente para agregar modo oscuro usando el sistema de variables CSS de Tailwind v4 y next-themes — evitando el destello de contenido sin estilo que afecta a las implementaciones ingenuas de localStorage.
Indicación principal
You are working in a Next.js App Router project with TypeScript and Tailwind CSS v4.
Task: add dark mode with system preference detection and a manual toggle.
Requirements:- Install `next-themes`.- In `src/app/layout.tsx`, wrap the app in `<ThemeProvider attribute="class" defaultTheme="system" enableSystem>`. The `ThemeProvider` is a Client Component — create a wrapper `src/components/Providers.tsx` if the root layout must remain a Server Component.- In `src/styles/global.css`, define CSS custom properties for both themes using the Tailwind v4 `@theme` directive: - Light: `--color-bg: oklch(100% 0 0)`, `--color-text: oklch(9% 0 0)`. - Dark (inside `[class="dark"]` selector): override those variables. Apply them to the body as `background: var(--color-bg)` and `color: var(--color-text)`.- Create `src/components/ThemeToggle.tsx` (Client Component) using `useTheme` from `next-themes`. It should cycle through light → dark → system on click and show a sun/moon/monitor icon. Use Tailwind's built-in `dark:` variant for icon visibility — do NOT use conditional classNames based on the `theme` string for icon color.- Do not use `tailwind.config.ts` `darkMode: 'class'` — that is Tailwind v3 API. In v4, the `dark:` variant is class-based by default.- Do NOT install lucide-react or any icon library — use SVG inline.
Stop and list all planned file changes before writing any code.Notas de implementación
- En Tailwind v4, el modo oscuro mediante el prefijo
dark:funciona automáticamente con la clase.darkenhtml— no se necesita entrada de configuración. next-themeslee el tema guardado delocalStoragey establece la clase antes del primer pintado, lo que previene el FOUC.- El
ThemeProviderdebe estar en el lado del cliente, pero ellayout.tsxraíz puede permanecer del lado del servidor extrayendo el proveedor a un componente envoltorioProviders.tsxmarcado como'use client'.
Cambios esperados en archivos
src/app/layout.tsx (edited — add Providers wrapper)src/components/Providers.tsx (new — Client Component with ThemeProvider)src/components/ThemeToggle.tsx (new — Client Component)src/styles/global.css (edited — CSS custom properties for light/dark)package.json (edited — add next-themes)Criterios de aceptación
- En la primera carga con el sistema configurado en oscuro, la página se renderiza oscura sin destello.
- Alternar ThemeToggle recorre los modos claro, oscuro y sistema; la preferencia persiste al recargar.
- Todas las utilidades
dark:de Tailwind existentes funcionan sin cambios de configuración. bun run buildtermina con código 0.
Comandos de prueba
bun add next-themesbun run typecheckbun run buildbun run dev# open DevTools, set system dark mode, reload — confirm no white flash# click ThemeToggle three times and confirm cycle: light → dark → systemErrores comunes de IA
- Agregar
darkMode: 'class'a untailwind.config.tsque no existe en un proyecto v4. - Envolver el Server Component raíz
layout.tsxcon'use client'en lugar de extraer un componente Providers. - Usar renderizado condicional
theme === 'dark'en lugar de la variantedark:de Tailwind, causando discrepancias de hidratación. - Olvidar
enableSystemenThemeProvider, haciendo que la detección de preferencia del sistema no funcione.
Indicación de corrección
There's a white flash on load or a hydration mismatch. Fix in order:1. Ensure `ThemeProvider` has `attribute="class"` and `enableSystem` props.2. Make sure `Providers.tsx` (not `layout.tsx`) is marked `'use client'`.3. Remove any `theme === 'dark'` conditional rendering from `ThemeToggle` — use `dark:` Tailwind variants instead so the server and client render the same HTML.Show only the corrected diff.