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

Evi*_*unk 3 reactjs react-i18next

我正在使用 react 应用程序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'
    }        
  });
Run Code Online (Sandbox Code Playgroud)

如果我在本地运行我的应用程序 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/",
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

反应应用程序文件正确加载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'
 }  
Run Code Online (Sandbox Code Playgroud)

然后它在生产中工作,但不再在本地工作:-/

我不确定如何避免这种情况?

fel*_*osh 5

您可以loadPath作为函数传递。

backend: {
  loadPath: () => {
    // check the domain
    const host = window.location.host;
    return (host === 'production.ltd' ? '/static/app':'') + '/static/app/static/locales/{{lng}}/{{ns}}.json';
  },
},
Run Code Online (Sandbox Code Playgroud)