yarn
yarn install glotstack
import * as React from 'react'
import { GlotstackProvider } from 'glotstack'
const importMethod = (locale: string) => {
// ใช้ fetch() จากไดเรกทอรีแบบคงที่เพื่อลดขนาดบันเดิล คุณจะต้องบันทึกคำแปลลงในตำแหน่งที่แน่นอน
return fetch(`/public/translations/${locale}.json`)
}
// // หรือใช้ inline require สำหรับคำแปลในตัว — ใช้งานได้แม้ไม่มีการสนับสนุน dynamic import
const translations: Record<string, () => Promise<Translations>> = {
'en-US': () => require('@/translations/en-US.json'),
'pl-PL': () => require('@/translations/pl-PL.json'),
'fr-FR': () => require('@/translations/fr-FR.json'),
};
const importMethod2 = (locale: string) => {
return translations[locale]();
}
const Application = () => {
const locale = 'en-US' // replace with your locale source
return (
<GlotstackProvider initialLocale={locale} importMethod={importMethod}>
{/*<YourComponent />*/}
</GlotstackProvider>
)
}
fetch()
ดึงไฟล์จากที่เก็บแบบสถิตที่คุณโฮสต์ได้ทุกที่ เช่น CDN - ช่วยให้ขนาดบันเดิลเล็กลงหากมีข้อจำกัด เช่น Cloudflare Workers fetch()
มักดีกว่า
ถ้าสภาพแวดล้อมไม่รองรับ dynamic import ให้ใช้ require()
แม้จะมีบูร์เลอร์เพลตมากขึ้น
แอปเล็กหรือ react-native แนะนำให้ใช้ require()
เพื่อบิลด์ไฟล์เข้าไปในบันเดิลโฮสต์useGlotstack()
ภายในคอมโพเนนต์ของคุณimport * as React from 'react'
import {useGlotstack} from 'glotstack'
function MyComponent() => {
const {t} = useGlotstack()
return (
<div>
{t('Quickstart.example', {assigns: {userName: 'JD'}})}
{/* Icon can be a function reference or a node */}
{t('Quickstart.example2', {assigns: {Icon: <Icon/>}})}
</div>
)
}
en-US.json
เราขอแนะนำให้วางไว้ในตำแหน่งเช่น ./translations/en-US.json
หากคุณกังวลเกี่ยวกับขนาดบันเดิล ให้ลดขนาดโดยการแยกไฟล์สาธารณะเช่น ./public/translations/en-US.json
.glotstack.json
ในโปรเจกต์ของคุณget-translations
yarn glotstack get-translations
yarn glotstack live-translate
export GLOTSTACK_API_KEY="q30NRNhCu4yWFswZYNfJzc3aou1w2VSaWukLHlshRU5xL1h1uYOZUUybgehT8QSgAL0PJGEE0GaulZu+08xOkw=="
yarn glotstack get-translations --source-path "./translations" --project-id "first-project" pl-PL fr-FR