Prompt para Adicionar Modo Escuro com Tailwind CSS v4
Prompt de agente de IA para adicionar modo escuro sensível ao sistema a um aplicativo Next.js usando variáveis CSS do Tailwind CSS v4 e next-themes, sem flash ao carregar.
CursorClaude CodeCodexWindsurf Next.jsTypeScriptTailwind
Forneça este prompt ao seu agente para adicionar modo escuro usando o theming baseado em variáveis CSS do Tailwind v4 e next-themes — prevenindo o flash de conteúdo não estilizado que afeta implementações ingênuas de localStorage.
Prompt 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 Implementação
- No Tailwind v4, o modo escuro via prefixo
dark:funciona com a classe.darknohtmlautomaticamente — nenhuma entrada de configuração é necessária. next-themeslê o tema salvo dolocalStoragee define a classe antes da primeira renderização, o que previne o FOUC (Flash de Conteúdo Não Estilizado).- O
ThemeProviderdeve ser do lado do cliente, mas olayout.tsxraiz pode permanecer do lado do servidor extraindo o provedor para um componente wrapperProviders.tsxmarcado com'use client'.
Alterações de Arquivos Esperadas
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)Critérios de Aceitação
- No primeiro carregamento com o sistema configurado para escuro, a página renderiza escura sem flash.
- Alternar o ThemeToggle percorre os modos claro, escuro e sistema; a preferência persiste ao recarregar.
- Todas as utilidades
dark:existentes do Tailwind funcionam sem alterações de configuração. bun run buildsai com código 0.
Comandos de Teste
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 → systemErros Comuns de IA
- Adicionar
darkMode: 'class'a umtailwind.config.tsque não existe em um projeto v4. - Envolver o Componente Servidor raiz
layout.tsxcom'use client'em vez de extrair um componente Providers. - Usar renderização condicional
theme === 'dark'em vez da variantedark:do Tailwind, causando incompatibilidades de hidratação. - Esquecer
enableSystemnoThemeProvider, tornando a detecção de preferência do sistema não funcional.
Prompt de Correção
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.