【问题标题】:nextjs with i18next and i18next-node-fs-backendnextjs 与 i18next 和 i18next-node-fs-backend
【发布时间】:2019-08-05 17:00:41
【问题描述】:

我正在开发一个多语言网站,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文件?

【问题讨论】:

    标签: reactjs next.js i18next


    【解决方案1】:

    烧了一天之后,我发现了如何做到这一点。我使用 i18next-fetch-backend(实际上在这个库中几乎没有编辑,我将发送 PR),在我的 i18n.js 组件中,添加 isomorphic-fetch 作为配置 obj 中的常规获取 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 : (() => {}),
    

    【讨论】:

    • 这是一个解决方案。但它有一个巨大的警告,即会减慢每个 SSR 请求的初始加载时间,因为它必须等待本地文件加载。所以我们需要慎重考虑。顺便说一句,我不明白为什么 next.js 即使在服务器端也无法识别 fs 模块。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2021-08-09
    • 2013-03-02
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    相关资源
    最近更新 更多