Add Darkmode to sveltekit
How to add darkmode to a sveltekit project
hooks.server.ts
import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
const darkMode: Handle = async ({ event, resolve }) => {
const darkModeCookie = event.cookies.get('darkmode') === 'true';
const response = await resolve(event, {
transformPageChunk: ({ html }) => html.replace('%darkmode%', darkModeCookie ? 'dark' : '')
});
return response;
};
export const handle = sequence(darkMode);
app.html
<body class="%darkmode%">
If you are using tailwind edit the following config
tailwind.config.csj
module.exports = {
darkMode: 'selector'
}
ToggleDarkmode.svelte
<script>
import { onMount } from 'svelte';
let isDarkMode = false;
function toggleDarkMode() {
isDarkMode = !isDarkMode;
document.cookie = `darkmode=${isDarkMode};path=/`;
document.body.classList.toggle('dark', isDarkMode);
}
onMount(() => {
isDarkMode = document.cookie.includes('darkmode=true');
document.body.classList.toggle('dark', isDarkMode);
});
</script>
<button on:click={toggleDarkMode}>
{isDarkMode ? '🌙' : '☀️'}
</button>
Now the body element is gonna have the dark
class once the cookie is set.