Skip to content

Svelte Usage

@avatar-generator/svelte provides an Avatar component that renders an <img> from any style. It works with Svelte 4 and Svelte 5; svelte is a peer dependency, so it uses whichever version your app pins.

Installation

Terminal window
pnpm add @avatar-generator/core @avatar-generator/svelte @avatar-generator/style-initials

Basic usage

<script lang="ts">
import Avatar from "@avatar-generator/svelte/Avatar.svelte";
import { initials } from "@avatar-generator/style-initials";
export let userId: string;
export let userName: string;
</script>
<Avatar style={initials} options={{ seed: userId, name: userName, size: 48 }} alt={userName} />

You can also import from the package root:

import Avatar from "@avatar-generator/svelte";

Svelte’s build tooling resolves the "svelte" export condition to the component itself, so both imports work identically.

Using different styles

<script lang="ts">
import Avatar from "@avatar-generator/svelte/Avatar.svelte";
import { initials } from "@avatar-generator/style-initials";
import { gradient } from "@avatar-generator/style-gradient";
import { emoji } from "@avatar-generator/style-emoji";
import { faces } from "@avatar-generator/style-faces";
const common = { seed: "Hugo GB", size: 64 };
</script>
<Avatar style={initials} options={common} alt="Initials" />
<Avatar style={gradient} options={common} alt="Gradient" />
<Avatar style={emoji} options={common} alt="Emoji" />
<Avatar style={faces} options={common} alt="Faces" />

All eleven styles work the same way — see the Style Gallery.

TypeScript

Import the option type from the style package:

import { initials, type InitialsOptions } from "@avatar-generator/style-initials";
const options: InitialsOptions = { seed: "user-123", name: "Hugo GB", fontWeight: 700 };

Props

PropTypeDefaultDescription
styleStyle<T>(required)The style object to render with
optionsT extends AvatarOptions(required)Seed and style-specific options
altstring"Avatar"Alt text for the <img>
classstring""Class applied to the <img>

The component regenerates reactively, so reassigning style or options re-renders the avatar.

Server-side rendering

Safe in SvelteKit: createAvatar returns a string and touches no browser globals, so the avatar renders during SSR with nothing left to hydrate.