nextjs 与 i18next 和 i18next-node-fs-backend

nextjs with i18next and i18next-node-fs-backend

我正在开发一个多语言站点,nextjs 用于 SSR,i18next 用于制作多语言机制。

由于使用下一个 SSR,我无法使用 i18next-xhr-backend,我应该使用 i18next-node-fs-backend 但在这种情况下,我为 fs 找出了这个错误:

Module not found: Can't resolve 'fs' in '/Users/macbook/Desktop/project/node_modules/i18next-node-fs-backend/lib'

是否有任何通用的方法来获取 i18next 语言 json 文件?

烧了一天后,我找到了方法。我使用 i18next-fetch-backend(实际上在这个库中几乎没有编辑,我将发送 PR),在我的 i18n.js 组件中,在配置中添加 isomorphic-fetch 作为常规获取 API对象

import i18n from 'i18next'
import Backend from 'i18next-fetch-backend'
import { initReactI18next } from 'react-i18next'
import fetch from 'isomorphic-fetch'

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    lng: 'fa',
    backend: {
      /* translation file path */
      loadPath: '/static/i18n/{{ns}}/{{lng}}.json',
      fetch
    },
    fallbackLng: 'fa',
    debug: true,
    /* can have multiple namespace, in case you want to divide a huge translation into smaller pieces and load them on demand */
    ns: ['translations'],
    defaultNS: 'translations',
    keySeparator: false,
    interpolation: {
      escapeValue: false,
      formatSeparator: ','
    },
    react: {
      wait: true
    }
  })

export default i18n

对于 i18next-fetch-backend 库,我在 i18next-fetch-backend.cjs.js 文件的第 181 行为默认配置添加以下条件:

  fetch: typeof fetch === "function" ? fetch : (() => {}),