国际化

使用 Gem 的国际化模块,你可以很迅速的为你的应用添加多语言支持。

开始

import { I18n } from '@mantou/gem/helper/i18n';

const en = {
  title: 'This is I18n',
};

const i18n = new I18n({
  fallbackLanguage: 'en',
  resources: {
    en,
    zh: () => import('./locales/zh.json'),
  },
});

console.log(i18n.get('title'));

实例化 I18n 对象时会自动根据浏览器设置选择适当的语言。语言包可以是对象,也可以是加载函数,以实现按需加载。

TIP

建议使用 Crowdin,Pontoon 类似的服务来维护你的语言包

在元素中可以直接使用 i18n.get('title') 来读取语言包中的值。

@customElement('app-root')
class App extends GemElement {
  @template()
  #content = () => {
    return html`
      <button @click=${() => i18n.setLanguage('zh')}>zh</button>
      <p>${i18n.get('title')}</p>
    `;
  };
}

按需加载

语言包可以是加载函数,配合打包工具的动态导入,每个语言打包成单独的文件,只加载用到的语言:

const i18n = new I18n({
  fallbackLanguage: 'en',
  resources: {
    en: () => import('./locales/en.json'),
    zh: () => import('./locales/zh.json'),
  },
});

加载函数可以返回语言包,也可以返回 default 导出语言包的模块。get 的参数类型从加载的语言包推断。语言包不在打包范围内时,可以在加载函数中请求,例如 () => fetch('/locales/zh.json').then((res) => res.json())。

当前语言包中缺少的条目使用后备语言(fallbackLanguage)中的值,后备语言的语言包只在读取缺少的条目时才加载,加载完成后自动更新元素。

加载函数是异步的,语言包加载完成前 get 返回后备语言中的值,后备语言也没有加载时返回 [key]。纯客户端渲染时,在首次渲染前等待 i18n.ready,避免先显示占位再切换,开启缓存时有缓存的语言包不需要等待加载:

await i18n.ready;
render(html`<app-root></app-root>`, document.body);

需要同步显示的语言(例如默认语言)可以直接导入语言包对象,只有其他语言按需加载。服务端渲染时客户端使用服务端输出的语言包,不需要等待,见服务端渲染。

缓存

使用 cache 缓存用户选择的语言,在用户下次进入 App 时直接使用,缓存数据将保存到 localStorage。为 'manual' 时需要调用 setCache 缓存。库中使用 I18n 时需要设置 cachePrefix,避免和应用中的缓存冲突。

开启 cache 后,加载函数加载的语言包也会缓存。下次使用这个语言时先同步使用缓存,同时调用加载函数,加载完成后更新缓存,内容变化时自动更新元素。每个模块只保留正在使用的语言和后备语言的缓存。子模块使用主模块的 cache 设置,只缓存语言包,不缓存语言。

const i18n = new I18n({
  cache: true,
  fallbackLanguage: 'en',
  resources: {
    en,
    zh: () => import('./locales/zh.json'),
  },
});

变量替换

在多语言项目中,常常有变量嵌入的情况,例如:

html`Hello, ${username}`;

使用 Gem 时,你可以使用 $ 标记变量,例如:

const i18n = new I18n({
  fallbackLanguage: 'en',
  resources: {
    en: {
      hello: 'Hello, $1! $2=> $1, Hello!',
    },
  },
});

html`${i18n.get('hello', 'World', 'reverse')}`;

// Hello, World! reverse=> World, Hello!

变量也可以是一个自定义渲染函数,它能将语言模版中提供的内容进行自定义渲染,下面的例子就是将语言条目中指定的单词 detail 渲染成链接:

const i18n = new I18n({
  fallbackLanguage: 'en',
  resources: {
    en: {
      detail: 'See $1<detail>, $1<detail2>',
    },
  },
});

html`${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}`;

URL 中指定语言

一般会为不同的语言生成唯一的 URL,因为这样能让搜索引擎进行准确的索引。I18n 在实例化时根据 urlParamsType 检查 URL,它支持:

  • path:根路径,例如 /zh/home
  • querystring:查询字符串,名称使用 urlParamsName 指定
  • ccTLD:国家代码顶级域名,例如 website.jp
  • gTLD:通用顶级域名下的子域名,例如 jp.website.com
const i18n = new I18n({
  fallbackLanguage: 'en',
  urlParamsType: 'ccTLD',
  resources: {
    en: {
      title: 'This is I18n',
    },
  },
});

TIP

当 urlParamsType 为 path 或者 querystring, 页面中的链接、history 路由切换都需要修改。 例如,urlParamsType 为 path 时可以通过设置 history.basePath 来全局定义此操作:

new I18n({
  urlParamsType: 'path',
  fallbackLanguage: 'zh-CN',
  resources: {
    'zh-CN': zhCN,
  },
  onChange(lang) {
    if (!history.basePath) {
      history.basePath = '/' + lang;
      const { path, query, hash } = history.getParams();
      history.replace({ path, query, hash });
    } else {
      const { path, query, hash } = history.getParams();
      history.basePath = '/' + lang;
      history.replace({ path, query, hash });
    }
  },
});

子模块

I18n.createSubModule 创建子模块,你可以按路由分割语言包,加快首屏渲染速度。子模块跟随主模块切换语言,使用主模块的后备语言和缓存设置,不修改文档的 lang 属性,只缓存语言包,不缓存语言:

// 在路由对应的模块中
const pageI18n = i18n.createSubModule('page', {
  en: () => import('./locales/page/en.json'),
  zh: () => import('./locales/page/zh.json'),
});

html`${pageI18n.get('title')}`;

子模块创建时开始加载当前语言的语言包,加载完成前 get 返回 [key]。i18n.ready 在主模块和所有子模块切换语言完成后 resolve,渲染刚加载的模块前等待它可以避免闪烁:

const { default: Page } = await import('./page');
await i18n.ready;

主模块的 setLanguage 也会等待所有子模块切换完成。

服务端渲染

使用 @mantou/gem-ssr 渲染时,每个请求有独立的语言,在请求中调用 setLanguage 设置。渲染结束后,请求中调用过 get 的模块会把当前语言的语言包(包含后备语言中的值)和 store 一起输出到页面中,没有使用的模块和其他语言不会输出:

await runInRequest(async () => {
  await i18n.setLanguage('zh');
  return renderToString(html`<app-root></app-root>`);
});

客户端创建 I18n 和子模块时直接使用服务端输出的语言包,不会再加载,水合时内容和服务端一致。服务端需要同步读取后备语言中的值,所以会同时加载当前语言和后备语言。

本地化

可以使用 <gem-route> 根据不同语言渲染不同的内容,只需要将 trigger 指定为 i18n 即可,例如:

const localizeRoutes = [
  {
    pattern: 'zh-*',
    async getContent() {
      import('...');
      return html`other element`;
    },
  },
];

html`<gem-route .trigger=${i18n} .routes=${localizeRoutes}></gem-route>`;

例子

import { render } from '@mantou/gem';
import { I18n } from '@mantou/gem/helper/i18n';
import type { RouteItem } from 'duoyun-ui/elements/route';

const en = {
  title: 'This is I18n',
  hello: 'Hello, $1! $2=> $1, Hello!',
  detail: 'See $1<detail>, $1<detail2>',
};
const i18n = new I18n<typeof en>({
  cache: true,
  fallbackLanguage: 'en',
  resources: {
    en,
    de: {
      title: 'Das ist I18n',
    },
    // 按需加载,也可以是 `() => import('./zh.json')`
    zh: async () => ({ title: '这是 I18n' }),
  },
  onChange: console.log,
});

const i18nModule = i18n.createSubModule<typeof en>('test', {
  en,
  de: {
    title: 'Das ist I18n',
  },
  zh: async () => {
    await new Promise((res) => setTimeout(res, 1000));
    return { title: '这是 I18n' };
  },
});

const localizeRoutes: RouteItem[] = [
  {
    pattern: 'en',
    getContent() {
      return html`en element`;
    },
  },
  {
    pattern: 'de',
    getContent() {
      return html`de element`;
    },
  },
  {
    pattern: '*',
    getContent() {
      return html`other element`;
    },
  },
];

@customElement('app-root')
export class App extends GemElement {
  @template()
  #render = () => {
    return html`
      <button @click=${() => i18n.setLanguage('de')}>de</button>
      <button @click=${() => i18n.setLanguage('zh')}>zh</button>
      <button @click=${() => i18n.setLanguage('en')}>en</button>
      <button @click=${() => i18n.resetLanguage()}>reset</button>
      <p>Current language: ${i18n.currentLanguage}</p>
      <p>${i18n.get('title')}</p>
      <p>${i18n.get('hello', 'World', 'reverse')}</p>
      <p>${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}</p>

      <h2>sub module</h2>
      <p>${i18nModule.get('title')}</p>
      <p>${i18nModule.get('hello', 'World', 'reverse')}</p>
      <p>${i18nModule.get('detail', (s) => html`<a href="#">${s}</a>`)}</p>

      <h2>localize content</h2>
      <dy-route .trigger=${i18n} .routes=${localizeRoutes}></dy-route>
    `;
  };
}

render(
  html`
    <gem-examples-layout>
      <app-root></app-root>
    </gem-examples-layout>
  `,
  document.body,
);