A modern, flash-free theme switcher component for SvelteKit 5 applications using DaisyUI themes with persistent storage.
$state
runes for global reactivitygit clone https://github.com/MSAZ89/sveltekit-tailwind-daisyui-TS-with-Theme-Switcher.git
cd sveltekit-tailwind-daisyui-TS-with-Theme-Switcher
npm i
npm run dev
src/lib/theme.svelte.ts
Global theme state using Svelte 5's $state
rune. Handles theme persistence and HTML attribute updates.
src/lib/components/ThemeSwitcher.svelte
Reusable theme switcher component with DaisyUI styling.
src/app.html
Contains the critical theme initialization script that prevents flash-of-unstyled-content (FOUC).
src/routes/app.css
Global CSS file where DaisyUI is imported and configured.
<!-- +page.svelte -->
<script lang="ts">
import ThemeSwitcher from '$lib/components/ThemeSwitcher.svelte';
import { theme } from '$lib/theme.svelte';
</script>
<div class="min-h-screen bg-base-100">
<div class="container mx-auto p-8">
<h1 class="text-4xl font-bold text-base-content mb-8">My App</h1>
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h2 class="card-title">Theme Switcher</h2>
<p>Current theme: <span class="badge badge-primary">{theme.current}</span></p>
<ThemeSwitcher class="mt-4" />
</div>
</div>
</div>
</div>
<script lang="ts">
import { theme } from '$lib/theme.svelte';
// Programmatically change theme
function setDarkMode() {
theme.set('dark');
}
// React to theme changes
$effect(() => {
console.log('Theme changed to:', theme.current);
});
</script>
import { theme } from '$lib/theme.svelte';
// Get current theme
theme.current; // 'light' | 'dark' | 'cupcake' | ...
// Set new theme
theme.set('dark');
<ThemeSwitcher class="custom-classes" />
Props:
class
(optional): Additional CSS classes for stylingAll 35 official DaisyUI themes are supported:
light
, dark
, cupcake
, bumblebee
, emerald
, corporate
, synthwave
, retro
, cyberpunk
, valentine
, halloween
, garden
, forest
, aqua
, lofi
, pastel
, fantasy
, wireframe
, black
, luxury
, dracula
, cmyk
, autumn
, business
, acid
, lemonade
, night
, coffee
, winter
, dim
, nord
, sunset
, caramellatte
, abyss
, silk
app.html
sets theme before page renders$state
provides global reactivity across componentsdata-theme
attribute on <html>
for DaisyUI@config {
plugins: {
daisyui: {
themes:
[ 'light',
'dark',
'your-custom-theme'];
}
}
}
// In theme.svelte.ts
export const THEMES = [...existingThemes, 'your-custom-theme'] as const;
<ThemeSwitcher class="w-48 max-w-none" />
Feel free to submit issues and enhancement requests!
MIT License - feel free to use in your projects.
Built with ❤️ using SvelteKit 5 and DaisyUI