i18next-serverside-config.ts 882 B

1234567891011121314151617181920212223242526
  1. import { createInstance } from 'i18next'
  2. import resourcesToBackend from 'i18next-resources-to-backend'
  3. import { initReactI18next } from 'react-i18next/initReactI18next'
  4. import { Locale } from '.'
  5. // https://locize.com/blog/next-13-app-dir-i18n/
  6. const initI18next = async (lng: Locale, ns: string) => {
  7. const i18nInstance = createInstance()
  8. await i18nInstance
  9. .use(initReactI18next)
  10. .use(resourcesToBackend((language: string, namespace: string) => import(`./lang/${namespace}.${language}.ts`)))
  11. .init({
  12. lng: lng === 'zh-Hans' ? 'zh' : lng,
  13. ns,
  14. fallbackLng: 'en',
  15. })
  16. return i18nInstance
  17. }
  18. export async function useTranslation(lng: Locale, ns = '', options: Record<string, any> = {}) {
  19. const i18nextInstance = await initI18next(lng, ns)
  20. return {
  21. t: i18nextInstance.getFixedT(lng, ns, options.keyPrefix),
  22. i18n: i18nextInstance
  23. }
  24. }