Adding a Dark Mode to a Svelte Site
Published: July 7, 2021
Interested in including a dark mode to your Sapper site?
Research argues that the dark background is better for reading on screens, this article, for exemplo, states similar conclusions After using the dark mode consistently for 7 years at work and in my personal life, I can say these findings are real. That's why I decided to add it to my personal blog.
This tutorial is adapted from another written by Sapper's official community. It is easy-pease, lemon-squeeze - but, wait... Sapper makes my life a little bit more difficult because it requires setting the variable for the dark mode state in the javascript window variable. To get started, it is necessary to create a 'darkMode.svelte' file, in my case in this path src/components/darkMode.svelte, and
<script>
window.document.body.classList.toggle('dark-mode')
</script>
<button on:click={toggle}>
{#if darkMode === true }
Light mode
{:else}
Dark mode
{/if}
</button>
<style>
button {
background: var(--bg-color);
border: 2px solid var(--text-color);
border-radius: 5px;
color: var(--text-color);
padding: 10px 15px;
}
button:active {
background: inherit;
}
</style>
Then, just import open the targeted view and the library in the script tag:
<script>
import Toggle from './toggle.svelte';
</script>
<header>
<Toggle />
</header>
Voilà!