Chuyển tới nội dung chính

Đa ngôn ngữ

Framework tự động lấy locale từ host (V-App, ChatGPT, ...) và truyền vào widget. Widget dùng hook useTranslate từ @v-miniapp/ui-react để hiển thị văn bản theo đúng ngôn ngữ người dùng. Ngôn ngữ trên widget sẽ thay đổi khi người dùng thay đổi trong cài đặt của host.

Locale được lấy từ hostContext.locale (chuẩn BCP 47) — một trong các thuộc tính của Host Context.

Thiết lập

1. Tạo file locale

Tạo các file JSON trong web/src/locales/, mỗi ngôn ngữ một file:

web/src/locales/vi.json
{
"greeting": "Xin chào",
"add": "Thêm",
"add.placeholder": "Bạn cần làm gì?"
}
web/src/locales/en.json
{
"greeting": "Hello",
"add": "Add",
"add.placeholder": "What do you need to do?"
}

2. Khởi tạo locale

Tạo file web/src/locales/index.ts để đăng ký các ngôn ngữ bằng initLocales:

web/src/locales/index.ts
import { initLocales } from '@v-miniapp/ui-react'
import en from './en.json'
import vi from './vi.json'

initLocales({
resources: { en, vi },
})

Sau đó import file này trong widget entry point:

web/src/widgets/my-widget/index.tsx
import { renderWidget } from '@v-miniapp/ai/web'
import '../../locales'
import { MyWidget } from './MyWidget'

renderWidget(<MyWidget />)
mẹo

import '../../locales' chỉ cần gọi một lần tại entry point của widget — tất cả component con đều dùng được useTranslate mà không cần import lại.

3. Dùng hook useTranslate

import { useTranslate } from '@v-miniapp/ui-react'

function MyWidget() {
const t = useTranslate()

return (
<div>
<p>{t('greeting')}</p>
<input placeholder={t('add.placeholder')} />
<button>{t('add')}</button>
</div>
)
}

Type-safe translation keys

Để TypeScript kiểm tra key hợp lệ, khai báo augmentation trong web/src/global.d.ts:

web/src/global.d.ts
import type vi from './locales/vi.json'

declare module '@v-miniapp/ui-react' {
interface ICustomLocales {
resource: typeof vi
}
}

Sau khi khai báo, t('greeting') sẽ được TypeScript kiểm tra — dùng key không tồn tại trong file locale sẽ báo lỗi ngay lúc build.