为什么我们应该在react-i18中使用http加载翻译



我正在阅读React-i18指令,他们共享了这个片段

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// not like to use this?
// have a look at the Quick start guide 
// for passing in lng and translations on init
i18n
// load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.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({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
}
});

export default i18n;

从代码片段来看,它说

// load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)

通过http加载json有什么优势?难道我们不能直接导入json而不是发出http请求吗?

导入JSON文件意味着你的应用程序中已经有了完整的文件(包括所有翻译([BUILDTIME]。请求外部文件使您有机会使用新密钥更新该文件或修改现有密钥[RUNTIME]

修改你想在ts/js文件中导入的文件需要重建整个应用程序

除了@user0101所说的,您还可以只为必要的页面加载翻译。它也可以通过分块来完成,但这比从后端获取翻译更困难。

最新更新