React i18next Backend-Path 在本地和生产环境中不同

2024-05-08

我正在使用一个反应应用程序react-i18next并加载翻译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

我现在面临的问题是,在生产中,应用程序不是从根目录提供服务,而是通过子文件夹提供构建的文件。因此我改变了我的packages.json并添加了homepage

{
  "name": "myapp",
  "version": "0.1.0",
  "homepage": "/static/app/",
  ...
}

构建应用程序并将其部署到产品上后,它仍然可以正确加载,但找不到翻译文件。

http://product.tld/static/app/index.html http://production.tld/static/app/index.html

反应应用程序文件已正确加载http://生产.tld/static/app/static/js/main http://production.tld/static/app/static/js/main*.js

但翻译文件仍然由http://product.tld/static/locales/de/translation.json http://production.tld/static/locales/de/translation.json不再可用(而是http://product.tld/static/app/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 as function.

backend: {
  loadPath: () => {
    // check the domain
    const host = window.location.host;
    return (host === 'production.ltd' ? '/static/app':'') + '/static/app/static/locales/{{lng}}/{{ns}}.json';
  },
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React i18next Backend-Path 在本地和生产环境中不同 的相关文章

随机推荐