i18n

File i18n

Trong plugin, các file đa ngôn ngữ của cả phía client và server đều được đặt trong thư mục src/locale.

|- /plugin-i18n
  |- /src
    |- /locale      # Thư mục đa ngôn ngữ
      |- en-US.ts   # Ngôn ngữ tiếng Anh
      |- zh-CN.ts   # Ngôn ngữ tiếng Trung

Bạn chỉ cần thêm các mục dịch vào file ngôn ngữ tương ứng (/src/locale/${lang}.ts). Nếu là lần đầu thêm file đa ngôn ngữ, bạn cần khởi động lại ứng dụng để có hiệu lực. Bạn có thể xem API app:getLang để kiểm tra xem các mục dịch đã được thêm thành công hay chưa.

Địa chỉ mặc định: http://localhost:13000/api/app:getLang?locale=zh-CN

Các API liên quan đến i18n

  • server
    • app.i18n
    • app.t(text, options)
    • ctx.i18n
    • ctx.t(text, options)
    • plugin.t()
  • client
    • ctx.i18n
    • ctx.t(text, options)
    • plugin.t()
    • useT()
  • utils
    • tExpr(text, options)
  • react-i18next
    • useTranslation(ns)
    • withTranslation(ns)

Server

app.i18n server

app.i18n là instance i18n toàn cục, thường được dùng trong CLI. Ví dụ kết hợp với inquirer để triển khai tương tác dòng lệnh.

import select from '@inquirer/select';
import input from '@inquirer/input';

export class PluginSampleI18nServer extends Plugin {
  load() {
    this.app.command('test-i18n').action(async () => {
      const answer1 = await select({
        message: 'Select a language',
        choices: [
          {
            name: '中文',
            value: 'zh-CN',
          },
          {
            name: 'English',
            value: 'en-US',
          },
        ],
      });
      await this.app.i18n.changeLanguage(answer1);
      const answer2 = await input({
        message: this.app.i18n.t('Enter your name'),
      });
      console.log(this.app.i18n.t(`Your name is {{name}}`, { name: answer2 }));
    });
  }
}

app.t(text, options) server

ctx.i18n server

ctx.i18n là cloneInstance của app.i18n toàn cục. ctx của mỗi request hoàn toàn độc lập, phản hồi thông tin đa ngôn ngữ theo ngôn ngữ của client.

Tham số request từ client có thể đặt trong query string

GET /?locale=en-US HTTP/1.1
Host: localhost:13000

Hoặc đặt trong request headers (khuyến nghị)

GET / HTTP/1.1
Host: localhost:13000
X-Locale: en-US

Ví dụ

export class PluginSampleI18nServer extends Plugin {
  load() {
    this.app.use(async (ctx, next) => {
      if (ctx.path === '/api/test-i18n') {
        ctx.body = `${ctx.i18n.t('Hello')} ${ctx.i18n.t('World')}`;
      }
      await next();
    });
  }
}

Xem http://localhost:13000/api/test-i18n?locale=zh-CN

ctx.t(text, options) server

plugin.t() server

Client

ctx.i18n client

ctx.t(text, options) client

plugin.t()

useT()

Hàm tiện ích

tExpr(text) server client

react-i18next

useTranslation(ns) client

withTranslation(ns) client