← 返回 Skill 列表
extension
分类: 开发与工程API Key 暂未确认

intlayer-svelte

将Intlayer国际化与Svelte和SvelteKit应用程序集成。当用户要求“设置Svelte i18n”、创建新的翻译组件、使用“useIntlayer”存储或配置提供程序时使用。

person作者: jakexiaohubgithub

Intlayer Svelte Usage

Core Philosophy

Intlayer promotes Component-Level Content Declaration. Instead of a massive global translation file, content is declared in *.content.ts files adjacent to the Svelte components that use them.

Workflow

To create a translated component, you need two files:

  1. Declaration: A content file (e.g., myComponent.content.ts) defining the dictionary.
  2. Implementation: A Svelte component (e.g., MyComponent.svelte) using the useIntlayer store.

1. Declare Content

Create a content file using t() for translations. File: src/components/MyComponent/myComponent.content.ts

import { t, type Dictionary } from "intlayer";

const content = {
  // The 'key' must be unique and matches what you pass to useIntlayer()
  key: "my-component",
  content: {
    text: t({
      en: "Welcome",
      fr: "Bienvenue",
      es: "Hola",
    }),
  },
} satisfies Dictionary;

export default content;

Setup

useIntlayer Hook

In Svelte, useIntlayer returns a store. You must use the $ prefix to access its value.

<script>
  import { useIntlayer } from "svelte-intlayer";
  const content = useIntlayer("my-component");
</script>

<div>
  <h1>
    {/* Return content */}
    {$content.text}
  </h1>
  {/* Return string (.value) */}
  <div aria-label={$content.text.value}></div>
</div>

Compiler

The Intlayer Compiler can extract all your content keys from your components, using one CLI command (npx intlayer extract) or automatically at app build.

It activates once compiler.enabled and compiler.output are set: .svelte files additionally require @intlayer/svelte-compiler.

References

Environments

Concepts

Packages