i18next.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import path from 'path';
  2. import type { Lang } from '@growi/core';
  3. import type { TFunction, i18n } from 'i18next';
  4. import { createInstance } from 'i18next';
  5. import resourcesToBackend from 'i18next-resources-to-backend';
  6. import { defaultLang, initOptions } from '^/config/i18next.config';
  7. import { resolveFromRoot } from '~/utils/project-dir-utils';
  8. import { configManager } from './config-manager';
  9. const relativePathToLocalesRoot = path.relative(__dirname, resolveFromRoot('public/static/locales'));
  10. const initI18next = async(fallbackLng: Lang[] = [defaultLang]) => {
  11. const i18nInstance = createInstance();
  12. await i18nInstance
  13. .use(
  14. resourcesToBackend(
  15. (language: string, namespace: string) => {
  16. return import(path.join(relativePathToLocalesRoot, language, `${namespace}.json`));
  17. },
  18. ),
  19. )
  20. .init({
  21. ...initOptions,
  22. fallbackLng,
  23. });
  24. return i18nInstance;
  25. };
  26. type Translation = {
  27. t: TFunction,
  28. i18n: i18n
  29. }
  30. export async function getTranslation(lang?: Lang): Promise<Translation> {
  31. const globalLang = configManager.getConfig('crowi', 'app:globalLang') as Lang;
  32. const fixedLang = lang ?? globalLang;
  33. const i18nextInstance = await initI18next([fixedLang, defaultLang]);
  34. return {
  35. t: i18nextInstance.getFixedT(fixedLang),
  36. i18n: i18nextInstance,
  37. };
  38. }