Google Cloud:react-i18next 未在 React 应用程序中加载 json 翻译文件

Google Cloud: react-i18next not loading json translation files in React app

我遇到了与此处所述相同的问题 (),只是我的两个项目都已正确配置。

我的 i18n.js 配置设置如下。

import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import { reactI18nextModule } from 'react-i18next';

i18n
  .use(Backend)
  .use(reactI18nextModule)
  .init({
        interpolation: {
            // React already does escaping
            escapeValue: false
        },
        lng: 'en',
      fallbackLng: 'en',
      backend: {
        loadPath: '/locales/{{lng}}/translation.json',
        allowMultiLoading: true
      },
      debug: true,
      react: {
        wait: true
      }
  });

export default i18n;

我遇到了这个错误i18next::backendConnector: loading namespace translation for language en failed failed parsing locales/en/translation.json to json

我确保我的 locales 目录在我的 public 目录中。我还验证了 post npm run build locales 目录已复制到 build 目录。

在我的暂存环境中,我在 Chrome 开发工具上打开网络选项卡,然后在新选项卡中打开 translations.json。我被带到正确的 url https://example.com/locales/en/translation.json 但是我被重定向到我的 index.html

我想通了,我遗漏的部分是我正在部署到 Google 云,为此的配置要求我指定允许将哪些文件类型用作静态资源。我将 json 添加到我的配置中,现在可以使用了。

handlers:
- url: /(.*\.(html|css|js|png|jpg|woff|json))
  static_files: build/
  upload: build/(.*\.(html|css|js|png|jpg|woff|json))

在 App Engine Standard 中,您需要在 app.yaml 配置文件中使用一个处理程序将 URL 模式关联到上传的静态文件。您将使用正则表达式定义在为静态文件指定的路径中将被视为静态文件的扩展文件。

例如。来自 app.yaml configuration for static files in App Engine Standard.

handlers: - url: /(.*\.(gif|png|jpg))$ static_files: static/ upload: static/.*\.(gif|png|jpg)$

其中,

url = URL 将被视为静态文件路径的模式。
static_files = 静态文件的路径。
upload = 与部署应用程序时此处理程序将引用的所有文件的文件路径相匹配的正则表达式。