Alien with one eye depicting observer
build action status
npm package version types included downloads count node version licence
minified size minzipped size dependency count tree-shaking

Svelte Media Observer

Svelte Media observer is small utility media queries observer built for Svelte framework.

Try it in the Svelte REPL.

Getting started

The package is available via npm:

npm i svelte-media-observer

Usage

import { mediaObserver } from "svelte-media-observer";
import type { MediaQueries } from "svelte-media-observer";

const mediaQueries: MediaQueries<"small" | "medium" | "dark"> = [
  [ "small", "(max-width: 640px)" ],
  [ "medium", "(max-width: 935px)" ],
  [ "dark", "(prefers-color-scheme: dark)" ]
];

export const media = mediaObserver(mediaQueries);

observer contains all named media queries as Record<breakpointName: string, queryMatch: boolean>. It is build on svelte/stores, so the usage is the same:

<script>
  import { media } from "your-observer-path";
</script>

{#if $media.small}
  <NavMobile />
{:else}
  <NavDesktop />
{/if}

Note

It is a nice idea to create several observers depending on your need and the rate the media queries will change.

Issues

While using Typescript and ESLint for Svelte, you might meet some limitations to type-aware rules. Link to the issue.

<script>
  import { media } from "your-observer-path";
</script>

// incorrect no-unsafe-member-access error
{#if $media.small}
  <NavMobile />
{:else}
  <NavDesktop />
{/if}

Attribution

Observer alien was created by FreakAddL.

Top categories

Loading Svelte Themes