使用react-i18next时,如何将locales文件夹放在public外并配置?
问题原因
i18next-http-backend依赖HTTP请求加载静态翻译文件,但React项目的src属于源码目录,构建后不会被直接暴露为可访问的静态资源路径,所以你配置的../src/locales/{{lng}}/{{ns}}.json无法被HTTP请求访问到,这就是移到src目录后失效的核心原因。
解决方案
改用i18next-resources-to-backend替代HttpBackend,它通过Webpack的动态导入功能将src目录下的翻译文件打包进应用,同时支持懒加载,配合LocalStorageBackend依然可以实现缓存功能。
步骤1:安装依赖
npm install i18next-resources-to-backend
步骤2:修改i18n配置文件
替换原有HttpBackend相关配置,改为动态导入src下的翻译资源:
import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import ChainedBackend from "i18next-chained-backend"; import LocalStorageBackend from "i18next-localstorage-backend"; import resourcesToBackend from 'i18next-resources-to-backend'; i18n .use(initReactI18next) .use(ChainedBackend) .init({ lng: 'hi_IN', interpolation: { escapeValue: false, }, react: { useSuspense: true, }, saveMissing: true, backend: { backends: [ LocalStorageBackend, // 优先从本地缓存加载 resourcesToBackend((lng, ns) => import(`./locales/${lng}/${ns}.json`)) // 动态导入src下的翻译文件 ], backendOptions: [{ expirationTime: 7 * 24 * 60 * 60 * 1000 // 缓存有效期保持不变 }] } }); export default i18n;
路径说明
确保./locales/${lng}/${ns}.json是相对于当前i18n.js文件的正确路径。比如如果i18n.js在src根目录,locales也在src根目录,这个路径就正确;如果i18n.js在src/config下,路径要改成../locales/${lng}/${ns}.json。
内容的提问来源于stack exchange,提问作者Arijit Patra
相关产品推荐
相关产品推荐

