Astro

Wanna make your Astro project slick with dark mode? Here’s the playbook for getting that moody vibe on lock.

Inline Scripts

Astro supports inline scripts, so we can get localStorage and set the theme.

<script is:inline>
  const getThemePreference = () => {
    if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
      return localStorage.getItem('theme')
    }
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }
  const isDark = getThemePreference() === 'dark'
  document.documentElement.classList[isDark ? 'add' : 'remove']('dark')
 
  if (typeof localStorage !== 'undefined') {
    const observer = new MutationObserver(() => {
      const isDark = document.documentElement.classList.contains('dark')
      localStorage.setItem('theme', isDark ? 'dark' : 'light')
    })
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
  }
</script>

Theme Switcher

First, install the hq-icons package.

In the terminal, run the following command to begin:
npm i hq-icons

And then, add the following code the component where you want to use the theme switcher.