Skip to content
Astro Eclipse
Esc
↑↓navigate↵open⌘Jpreview
On this page

Getting started

Install Astro Eclipse, add the integration, write the theme CSS and switch themes from a button.

Install

npm install astro-eclipse
pnpm add astro-eclipse
yarn add astro-eclipse
bun add astro-eclipse
nub add astro-eclipse
aube add astro-eclipse

It needs Astro 5, 6 or 7 (^5 || ^6 || ^7). The package is ESM only.

Add the integration

import { defineConfig } from 'astro/config'
import eclipse from 'astro-eclipse'

export default defineConfig({
  integrations: [eclipse()],
})

With no options the themes are light and dark, the visitor’s system preference is the default, the theme is written to data-theme on <html>, and the choice is stored in localStorage under eclipse-theme. Every option is listed in the config reference.

The integration injects a small inline script into every <head>. It runs before first paint, which is why a reload never shows the wrong theme. See the head script.

Write the theme CSS

Astro Eclipse ships no palette. It sets data-theme="light" or data-theme="dark" on <html>, and you select on it:

:root {
  color-scheme: light;
  --bg: #fff;
  --fg: #111;
}

:root[data-theme='dark'] {
  color-scheme: dark;
  --bg: #000;
  --fg: #eee;
}

body {
  background: var(--bg);
  color: var(--fg);
}

Import the file in your layout. CSS variables covers more patterns, and Tailwind the class-based setup.

Switch the theme

toggleTheme() moves to the next theme in themes. Passing the click event as origin makes the reveal start where the visitor clicked.

<button type="button" id="theme-button" aria-label="Toggle dark mode">
  Theme
</button>

<script>
  import { toggleTheme } from 'astro-eclipse/client'

  document.querySelector('#theme-button')?.addEventListener('click', (event) => {
    toggleTheme({ origin: event })
  })
</script>

To pick a theme by name, or to let the visitor go back to following the system, use setTheme:

import { setTheme } from 'astro-eclipse/client'

setTheme('dark')
setTheme('system') // needs the themes "light" and "dark"

setTheme throws a RangeError for a name that is not in themes. The full list of functions is in the client API.

Next

A ready-made button

If you do not want to write the button, use the ThemeToggle component.

Was this page helpful?