我正在使用带有 react-i18next
的 react 应用程序并使用 i18next-xhr-backend
加载翻译
i18n
.use(Backend)
.use(initReactI18next) // passes i18n down to react-i18next
.init({
lng: "de",
backend: {
loadPath: '/static/locales/{{lng}}/{{ns}}.json'
}
});
如果我在本地运行它,我的应用程序将通过
http://localhost:3000/
提供服务并且翻译文件也很好地加载(src 位于
public/statuc/locales/
)http://localhost:3000/static/locales/de/translation.json
我现在面临的问题是,在生产中,应用程序不是从 root 提供的,而是通过子文件夹提供构建的文件。因此我改变了我的
packages.json
并添加 homepage
{
"name": "myapp",
"version": "0.1.0",
"homepage": "/static/app/",
...
}
构建应用程序并将其部署到 prod 后,它仍然可以正确加载,但找不到翻译文件。
http://production.tld/static/app/index.html
react 应用程序文件正确加载 http://production.tld/static/app/static/js/main *.js
但翻译文件仍由 http://production.tld/static/locales/de/translation.json 获取不再可用(取而代之的是 http://production.tld/static/app/static/locales/de/translation.json 是正确的)
我可以通过更改 i18n 配置来修复它
backend: {
loadPath: '/static/app/static(locales/{{lng}}/{{ns}}.json'
}
然后它在生产中工作,但不再在本地工作:-/
我不确定如何避免这种情况?
最佳答案
您可以通过loadPath
如 功能 .
backend: {
loadPath: () => {
// check the domain
const host = window.location.host;
return (host === 'production.ltd' ? '/static/app':'') + '/static/app/static/locales/{{lng}}/{{ns}}.json';
},
},
关于reactjs - React i18next Backend-Path 在本地和生产环境中不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59774175/