新しいレベルまであなたのsvelteの国際化をビーム


仕事が楽しいSvelte . デザインは、エレガントなビルディングブラウザーアプリの喜びを結合することができます堅牢な第一党の追加です.
進行中のJavaScriptフレームワークの最も有名なi 18 nプラグインSvelte でしょうsvelte-i18n .

Christian Kaisermann, thank you for this great i18n plugin!


このチュートリアルでは、追加の超大国を追加しますsvelte-i18n 😉

TOC

  • So how does a basic svelte-i18n setup look like? Let's get into it...

  • Is it possible to make a svelte-18n setup even better?
  • Prerequisites
  • Getting started
  • Language Switcher
  • Where are the additional superpowers?
  • How does this look like?
  • save missing translations
  • in context editing
  • 👀 but there's more...
  • 🎉🥳 Congratulations 🎊🎁
  • それでは、基本的なsvelte - i 18 nセットアップはどのように見えるのですか?

    それを始めましょう。


    必要条件

    Make sure you have Node.js and npm installed. It's best, if you have some experience with simple HTML, JavaScript and basic Svelte, before jumping to svelte-i18n .

    始める

    Take your own Svelte project or create a new one .
    svelet - i 18 n依存性をインストールしましょう.npm install svelte-i18nクリエイトアi18n.js ファイル
    import { addMessages, init, getLocaleFromNavigator } from 'svelte-i18n';
    
    const fallbackLocale = 'en';
    const lngs = [fallbackLocale, 'de'];
    
    addMessages('en', {
      welcome: 'Welcome to Your Svelte App'
    });
    addMessages('de', {
      welcome: 'Willkommen zu deiner Svelte-App'
    });
    
    let initialLocale;
    const detectedLocale = getLocaleFromNavigator(); // the locale could be region specific, i.e. de-CH
    if (lngs.indexOf(detectedLocale) > -1) initialLocale = detectedLocale;
    if (!initialLocale && detectedLocale.indexOf('-') > 0) {
      const foundLng = lngs.find((l) => detectedLocale.indexOf(l + '-') === 0);
      if (foundLng) initialLocale = foundLng;
    }
    if (!initialLocale) initialLocale = fallbackLocale;
    
    init({
      fallbackLocale,
      initialLocale
    });
    
    インポートi18n.js あなたのファイルmain.js ファイル
    import App from './App.svelte';
    
    import './i18n';
    
    const app = new App({
      target: document.body,
      props: {}
    });
    
    export default app;
    
    最初に国際化されたテキストを使おうとしましょう.
    テンプレートインポート_ からsvelte-i18n 以下のようにします.
    <script>
      import { _ } from 'svelte-i18n';
    </script>
    
    <main>
      <img alt="svelte logo" src="img/svelte-logo.png" />
      <h1>{$_('welcome')}</h1>
    </main>
    
    いいねそれでは別のテキスト要素を追加しましょう.
    <script>
      import { _ } from 'svelte-i18n';
    </script>
    
    <main>
      <img alt="svelte logo" src="img/svelte-logo.png" />
      <h1>{$_('welcome')}</h1>
      <p>{@html $_('descr', { values: { link: `<a href="https://svelte.dev/tutorial" target="_blank">${$_('doc')}</a>` } })}</p>
    </main>
    
    と対応する翻訳:
    addMessages('en', {
      welcome: 'Welcome to Your Svelte App',
      descr: 'Visit the {link} to learn how to build Svelte apps.',
      doc: 'Svelte tutorial'
    });
    addMessages('de', {
      welcome: 'Willkommen zu deiner Svelte-App',
      descr: 'Besuchen Sie den {link}, um zu erfahren, wie Sie Svelte-Apps erstellen.',
      doc: 'Svelte Tutorial'
    });
    
    さて、ブラウザの言語によっては以下のようになります.

    言語スイッチャー

    Now we will create a language switcher to make the content change between different languages.

    <script>
      import { _, locale, locales } from 'svelte-i18n';
    </script>
    
    <main>
      <img alt="svelte logo" src="img/svelte-logo.png" />
      <h1>{$_('welcome')}</h1>
      <p>{@html $_('descr', { values: { link: `<a href="https://svelte.dev/tutorial" target="_blank">${$_('doc')}</a>` } })}</p>
      <select bind:value={$locale}>
        {#each $locales as locale}
          <option value={locale}>{locale}</option>
        {/each}
      </select>
    </main>
    

    And we will store the current chosen language in the localStorage:

    import { addMessages, init, getLocaleFromNavigator, locale } from 'svelte-i18n';
    
    const fallbackLocale = 'en';
    const lngs = [fallbackLocale, 'de'];
    
    addMessages('en', {
      welcome: 'Welcome to Your Svelte App',
      descr: 'Visit the {link} to learn how to build Svelte apps.',
      doc: 'Svelte tutorial'
    });
    addMessages('de', {
      welcome: 'Willkommen zu deiner Svelte-App',
      descr: 'Besuchen Sie den {link}, um zu erfahren, wie Sie Svelte-Apps erstellen.',
      doc: 'Svelte Tutorial'
    });
    
    locale.subscribe((lng) => {
      if (lng) localStorage.setItem('svelte-i18n-locale', lng);
    });
    
    let initialLocale;
    const detectedLocale = localStorage.getItem('svelte-i18n-locale') || getLocaleFromNavigator(); // the locale could be region specific, i.e. de-CH
    if (lngs.indexOf(detectedLocale) > -1) initialLocale = detectedLocale;
    if (!initialLocale && detectedLocale.indexOf('-') > 0) {
      const foundLng = lngs.find((l) => detectedLocale.indexOf(l + '-') === 0);
      if (foundLng) initialLocale = foundLng;
    }
    if (!initialLocale) initialLocale = fallbackLocale;
    
    init({
      fallbackLocale,
      initialLocale
    });
    

    🥳 素晴らしい、あなただけの最初の言語スイッチャを作成しました!

    追加超大国はどこですか?

    Let's meet locizer ...
    locizer からのデータにアクセスする軽量モジュールですlocize プロジェクト内で使用します.


    これはどうですか。

    First you need to signup at locize and login .
    Then create a new project で検索し、あなたの翻訳を追加します.あなたの翻訳を追加することができますimporting the individual json files またはAPI またはCLI .
    あなたのコードファイルに翻訳を持っているが、トランスレータのために働くのに適していません.
    Locizeを使用すると、コードからの翻訳が分離されます.
    すべての翻訳をインポートするには、次のようになります.

    そうすれば、我々はインストールする予定ですlocizer .npm install locizer適応しましょうi18n.js ファイル
    import { register, init, getLocaleFromNavigator, locale } from 'svelte-i18n';
    import locizer from 'locizer';
    
    const fallbackLocale = 'en';
    const lngs = [fallbackLocale, 'de'];
    const namespace = 'messages'; // your namespace name added in locize
    
    locizer.init({
      projectId: 'your-locize-project-id'
    });
    
    lngs.forEach((l) => {
      register(l, () => new Promise((resolve, reject) => {
        locizer.load(namespace, l, (err, ns) => {
          if (err) return reject(err);
          resolve(ns);
        });
      }));
    })
    
    locale.subscribe((lng) => {
      if (lng) localStorage.setItem('svelte-i18n-locale', lng);
    });
    
    let initialLocale;
    const detectedLocale = localStorage.getItem('svelte-i18n-locale') || getLocaleFromNavigator();
    if (lngs.indexOf(detectedLocale) > -1) initialLocale = detectedLocale;
    if (!initialLocale && detectedLocale.indexOf('-') > 0) {
      const foundLng = lngs.find((l) => detectedLocale.indexOf(l + '-') === 0);
      if (foundLng) initialLocale = foundLng;
    }
    if (!initialLocale) initialLocale = fallbackLocale;
    
    init({
      fallbackLocale,
      initialLocale
    });
    
    翻訳が非同期に読み込まれているので、翻訳が準備されるまで読み込みメッセージを表示することもできます.
    <script>
      import { isLoading, _, locale, locales } from 'svelte-i18n';
    </script>
    
    <main>
      <img alt="svelte logo" src="img/svelte-logo.png" />
      {#if $isLoading}
        <p>
          loading translations...
        </p>
      {:else}
        <h1>{$_('welcome')}</h1>
        <p>{@html $_('descr', { values: { link: `<a href="https://svelte.dev/tutorial" target="_blank">${$_('doc')}</a>` } })}</p>
        <select bind:value={$locale}>
          {#each $locales as locale}
            <option value={locale}>{locale}</option>
          {/each}
        </select>
      {/if}
    </main>
    
    今すぐあなたの翻訳を直接からフェッチされますlocize CDN .
    🙀 これは、あなたのコードを変更したり、アプリケーションを再配置することなく、翻訳を修正することを意味します.🤩

    行方不明の翻訳を保存

    I wish newly added keys in the code, would automatically be saved to locize.

    Your wish is my command!

    Extend the i18n.js file with the locize api-key and the handleMissingMessage function:

    import { register, init, getLocaleFromNavigator, locale } from 'svelte-i18n';
    import locizer from 'locizer';
    
    const fallbackLocale = 'en';
    const lngs = [fallbackLocale, 'de'];
    const namespace = 'messages';
    const apiKey = 'my-api-key'; // do not expose your API-Key in production
    
    locizer.init({
      projectId: 'your-locize-project-id',
      apiKey
    });
    
    lngs.forEach((l) => {
      register(l, () => new Promise((resolve, reject) => {
        locizer.load(namespace, l, (err, ns) => {
          if (err) return reject(err);
          resolve(ns);
        });
      }));
    })
    
    locale.subscribe((lng) => {
      if (lng) localStorage.setItem('svelte-i18n-locale', lng);
    });
    
    let initialLocale;
    const detectedLocale = localStorage.getItem('svelte-i18n-locale') || getLocaleFromNavigator();
    if (lngs.indexOf(detectedLocale) > -1) initialLocale = detectedLocale;
    if (!initialLocale && detectedLocale.indexOf('-') > 0) {
      const foundLng = lngs.find((l) => detectedLocale.indexOf(l + '-') === 0);
      if (foundLng) initialLocale = foundLng;
    }
    if (!initialLocale) initialLocale = fallbackLocale;
    
    init({
      fallbackLocale,
      initialLocale,
      handleMissingMessage: apiKey ? ({ locale, id, defaultValue }) => {
        if (locale !== locizer.referenceLng) return;
        locizer.add(namespace, id, defaultValue);
      } : undefined
    });
    

    Now, if you add a new key in your templates, <h2>{$_('howAreYou', { default: 'How are you?' })}</h2> :

    <script>
      import { isLoading, _, locale, locales } from 'svelte-i18n';
    </script>
    
    <main>
      <img alt="svelte logo" src="img/svelte-logo.png" />
      {#if $isLoading}
        <p>
          loading translations...
        </p>
      {:else}
        <h1>{$_('welcome')}</h1>
        <h2>{$_('howAreYou', { default: 'How are you?' })}</h2>
        <p>{@html $_('descr', { values: { link: `<a href="https://svelte.dev/tutorial" target="_blank">${$_('doc')}</a>` } })}</p>
        <select bind:value={$locale}>
          {#each $locales as locale}
            <option value={locale}>{locale}</option>
          {/each}
        </select>
      {/if}
    </main>
    
    It gets automatically saved to locize:

    最後に、の助けを借りてauto-machinetranslation workflow , 新しいキーは、アプリケーションの開発中に自動的にローカライズされていないだけでなく、自動的に機械翻訳を使用してターゲット言語に変換されます:

    チェックアウトvideo 自動機械翻訳ワークフローがどのように見えるかを見るために!

    文脈編集中

    There's another cool think we can do...

    Let's install locize :npm install locize
    import { register, init, getLocaleFromNavigator, locale } from 'svelte-i18n';
    import locizer from 'locizer';
    import { addLocizeSavedHandler } from 'locize';
    
    const fallbackLocale = 'en';
    const lngs = [fallbackLocale, 'de'];
    const namespace = 'messages';
    const apiKey = 'my-api-key'; // do not expose your API-Key in production
    
    locizer.init({
      projectId: 'your-locize-project-id',
      apiKey
    });
    
    lngs.forEach((l) => {
      register(l, () => new Promise((resolve, reject) => {
        locizer.load(namespace, l, (err, ns) => {
          if (err) return reject(err);
          resolve(ns);
        });
      }));
    })
    
    locale.subscribe((lng) => {
      if (lng) localStorage.setItem('svelte-i18n-locale', lng);
    });
    
    let initialLocale;
    const detectedLocale = localStorage.getItem('svelte-i18n-locale') || getLocaleFromNavigator();
    if (lngs.indexOf(detectedLocale) > -1) initialLocale = detectedLocale;
    if (!initialLocale && detectedLocale.indexOf('-') > 0) {
      const foundLng = lngs.find((l) => detectedLocale.indexOf(l + '-') === 0);
      if (foundLng) initialLocale = foundLng;
    }
    if (!initialLocale) initialLocale = fallbackLocale;
    
    init({
      fallbackLocale,
      initialLocale,
      handleMissingMessage: apiKey ? ({ locale, id, defaultValue }) => {
        if (locale !== locizer.referenceLng) return;
        locizer.add(namespace, id, defaultValue);
      } : undefined
    });
    
    addLocizeSavedHandler(() => location.reload());
    
    今すぐロケイズを開きますInContext Editor そして驚いた.

    👀 しかし、より多く...

    Caching :

    Merging versions :

    🧑‍💻 コードが見つかるhere .

    🎉🥳 祝辞🎊🎁

    I hope you’ve learned a few new things about Svelte localization and modern localization workflows .
    だから次のレベルにあなたのI 18 Nのトピックを取る場合は、それを試してみる価値があるlocize .

    👍