npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

live-svelte-gettext

v0.1.1

Published

TypeScript client library for LiveSvelteGettext - runtime translations for Svelte components

Readme

LiveSvelteGettext

TypeScript client library for runtime translations in Svelte components. Part of the LiveSvelteGettext project.

Features

  • Type-safe translations - Full TypeScript support with type definitions
  • Variable interpolation - Replace %{var} placeholders with dynamic values
  • Plural handling - Simple English plural rules (count === 1 ? singular : plural)
  • Fallback support - Returns the key if translation not found
  • Zero dependencies - Lightweight and fast
  • 100% test coverage - Thoroughly tested with 48+ test cases

Installation

This library is typically installed automatically by the live_svelte_gettext Elixir package. If you need to install it manually:

npm install live-svelte-gettext

Or copy translations.ts directly into your Phoenix project at assets/js/translations.ts.

Usage

Basic Setup

import { initTranslations, gettext } from './translations';

// Initialize with translations from server
initTranslations({
  "Hello": "Hej",
  "Goodbye": "Hejdå",
  "Welcome, %{name}": "Välkommen, %{name}"
});

// Use translations
gettext("Hello"); // Returns "Hej"

In a Svelte Component

<script lang="ts">
  import { initTranslations, gettext, ngettext } from './translations';

  // Receive translations from LiveView
  export let translations: Record<string, string>;

  // Initialize on mount
  initTranslations(translations);

  let username = "Anna";
  let itemCount = 5;
</script>

<h1>{gettext("Welcome, %{name}", { name: username })}</h1>
<p>{ngettext("1 item", "%{count} items", itemCount)}</p>

With Phoenix LiveView

In your LiveView, pass translations to the Svelte component:

def render(assigns) do
  ~H"""
  <YourComponent
    translations={YourApp.SvelteStrings.all_translations()}
    {assigns}
  />
  """
end

API Reference

initTranslations(data)

Initialize the translation system with data from the server.

Parameters:

  • data: Record<string, string> - Translation key-value pairs

Example:

initTranslations({
  "Hello": "Hej",
  "Goodbye": "Hejdå"
});

gettext(key, vars?)

Get a translated string with optional variable interpolation.

Parameters:

  • key: string - The translation key (usually the English string)
  • vars?: Record<string, string | number> - Optional variables for interpolation

Returns: string - Translated string with variables replaced, or the key if not found

Examples:

gettext("Hello");
// Returns: "Hej"

gettext("Welcome, %{name}", { name: "Anna" });
// Returns: "Välkommen, Anna"

gettext("Missing key");
// Returns: "Missing key" (fallback)

ngettext(singular, plural, count, vars?)

Get a translated string with plural handling.

Parameters:

  • singular: string - Singular form (e.g., "1 item")
  • plural: string - Plural form (e.g., "%{count} items")
  • count: number - Number to determine singular/plural
  • vars?: Record<string, string | number> - Optional additional variables

Returns: string - Translated string with count and variables interpolated

Examples:

ngettext("1 item", "%{count} items", 1);
// Returns: "1 objekt"

ngettext("1 item", "%{count} items", 5);
// Returns: "5 objekt"

ngettext("%{user} has 1 item", "%{user} has %{count} items", 3, { user: "Anna" });
// Returns: "Anna har 3 objekt"

isInitialized()

Check if translations have been initialized.

Returns: boolean - true if initTranslations has been called

Example:

if (!isInitialized()) {
  console.warn("Translations not loaded yet");
}

resetTranslations()

Reset translations to empty state (useful for testing).

Example:

// In tests
beforeEach(() => {
  resetTranslations();
});

Interpolation

Variable interpolation uses the %{varname} syntax:

gettext("Hello %{first} %{last}", { first: "Anna", last: "Andersson" });
// Returns: "Hej Anna Andersson"

Features:

  • Supports both string and number values
  • Handles missing variables gracefully (leaves placeholder)
  • Escapes regex special characters in variable names
  • Replaces all occurrences of the same variable

Plural Rules

Currently uses simple English plural rules:

  • count === 1 → singular form
  • count !== 1 → plural form

Future versions will support CLDR plural rules for other languages.

TypeScript Support

Full TypeScript definitions included:

import type { TranslationVars } from './translations';

const vars: TranslationVars = {
  name: "Anna",
  count: 42
};

gettext("Hello %{name}, you have %{count}", vars);

Testing

Run tests:

npm test

Run tests with coverage:

npm run test:coverage

Build TypeScript:

npm run build

Edge Cases Handled

  • Escaped quotes (\", \')
  • Special characters in translations
  • Newlines in translation strings
  • Multiple occurrences of same variable
  • Regex special characters in variable names
  • Empty strings
  • Missing translations (fallback to key)
  • Swedish characters (åäö) and UTF-8

Browser Support

Requires ES2020 support:

  • Chrome 80+
  • Firefox 72+
  • Safari 13.1+
  • Edge 80+

License

MIT

Contributing

Part of the LiveSvelteGettext project. See the main repository for contribution guidelines.

Related Projects