繁体   English   中英

从后端加载翻译并与 react-i18next 一起使用

[英]Load transalatons from backend and use with react-i18next

我需要为 react js 项目实现翻译。

在我的项目src/locale/i18n.js文件中

 import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import Backend from 'i18next-http-backend'; i18n // detect user language // learn more: https://github.com/i18next/i18next-browser-languageDetector.use(Backend).use(LanguageDetector) // pass the i18n instance to react-i18next. .use(initReactI18next) // init i18next // for all options read: https://www.i18next.com/overview/configuration-options.init({ debug: true, fallbackLng: 'en', interpolation: { escapeValue: false, // not needed for react as it escapes by default }, }); export default i18n;

我将此文件导入 index.js

import './locales/i18n'
ReactDOM.render(
  <React.StrictMode>
    <Suspense fallback="Loading...">
      <App />

    </Suspense>
  </React.StrictMode>,
  document.getElementById('root')
);

在我的 app.js 中

import { useTranslation, Trans } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lang) => {
    i18n.changeLanguage(lang)
  }

  return (
    <div className="App">
      {t('description.part2')}
      <button onClick={() => changeLanguage('en')}>EN</button>
      <button onClick={() => changeLanguage('si')}>SI</button>

    </div>
  );
}

另外,我的翻译密钥放在public/locales/en/transalation.jsonpublic/locales/si/transalation.json

这个设置工作得很好。 但我需要从后端 API 加载我的翻译。 它有几个 JSON 文件,这是 URL 格式

BASEURL/locales/Language/NameSpace.json

它几乎没有命名空间,例如

报告

常见的

仪表板

所以如果为常见的 NameSpace 运行英文翻译,

BASEURL/locales/Language/NameSpace.json服务器返回一个 JSON object 这样

{
"com:search":"search",
"com:logout":"logout"
}

如何一次调用这些 API 端点并将其提供给 i18n 实例? 所以我可以像这样在项目的任何地方使用这些翻译键

   <h2>{t("common:com-description")}</h2>

我想这会更好,如果你写脚本来下载翻译到文件夹public/locales/si/transalation.json

update-i18n.js

const UpdateTranslation = async()=> {
 // get translation from backend
 const data = await fetch('url') 
 
 if (!fs.existsSync(`./public/locales`)) fs.mkdirSync(`./public/locales`);
  
 [data].forEach((lang) => {
  if (!fs.existsSync(`./public/locales/${lang}`)) 
    fs.mkdirSync(`./public/locales/${lang}`);
      fs.writeFile(
        `./public/locales/${lang}/common.json`,
        JSON.stringify(result[lang], null, 2),
        function (err) {
          if (err) return console.log('Error: ', err);
          console.log(`/public/locales/${lang}/common.json - updated`);
        }
      );
   }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM