即使已声明,也要保持 namespacesRequired

Keep having namespacesRequired even if declared

我已经为我的 NextJS 和 React 项目设置了 next-18next,翻译在我的项目中完美运行。

但我一直收到以下著名警告:

You have not declared a namespacesRequired array on your page-level component: withI18nextTranslation(Index). This will cause all namespaces to be sent down to the client, possibly negatively impacting the performance of your app. For more info, see: https://github.com/isaachinman/next-i18next#4-declaring-namespace-dependencies

我已经在我的每个页面级组件中声明了 namespacesRequired(404 页面除外,因为我在文档中读到您不能)

但是:

现在不知道去哪里看...这是触发警告的我的页面代码

import React from "react";
import IndexView from "../shared/views/index/index"
import i18nextInstance from "../i18n"

function Index() {
  return (
    <IndexView />
  );
};

Index.getInitialProps = async () => ({
  namespacesRequired: ["common"]
})

export default i18nextInstance.withTranslation("common")(Index);

这是我的 i18n 配置。

import NextI18Next from "next-i18next"

const nextI18next = new NextI18Next({
    defaultLanguage: "en",
    otherLanguages: ['fr'],
     localeSubpaths: {
          en: 'en',
          fr: 'fr'
      },
    fallbackLng: "en",
    serverLanguageDetection: false,
    browserLanguageDetection: false,
    detection: {
        // check if language is cached in cookies, if not check local storage
        order: ["cookie", "localStorage"],

        // next-i18next by default searches for the "next-i18next" cookie on server requests
        lookupCookie: "next-i18next",
        lookupLocalStorage: "i18nextLng",

        // cache the language in cookies and local storage
        caches: ["cookie", "localStorage"]
    },
    react: {
        // trigger a rerender when language is changed
        bindI18n: "languageChanged",
        // we're NOT using suspsense to detect when the translations have loaded
        useSuspense: false
    }
});


export default nextI18next;

我的server.js

const express = require('express')
const next = require('next')
const nextI18NextMiddleware = require('next-i18next/middleware').default
const nextI18next = require("./i18n")


const port = process.env.PORT || 3000
const app = next({ dev: process.env.NODE_ENV !== 'production' })
const handle = app.getRequestHandler();

(async () => {
    await app.prepare()
    const server = express()

    await nextI18next.initPromise
    server.use(nextI18NextMiddleware(nextI18next))

    server.get('*', (req, res) => handle(req, res))

    await server.listen(port)
    console.log(`> Ready on http://localhost:${port}`) // eslint-disable-line no-console
})()

我的 _app.js 终于将此作为导出行

export default nextI18next.appWithTranslation(App)

如果你们有任何想法,我会很高兴听到它:) 谢谢。

嗯,我没有使用 server.js,因为我忘记告诉 package.json 启动它。

"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"

现在错误消失了