我正在使用i18next翻译我的NextJs应用程序。翻译在我的浏览器中加载非常好,但在我的控制台中仍然很少看到错误。
i18next: hasLoadedNamespace: i18next was not initialized undefined
i18next::translator: key "resources.welcome_string.value" for languages "en-US" won't get resolved as namespace "myStrings" was not yet loaded This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!
i18next::translator: missingKey undefined myStrings resources.welcome_string.value resources.welcome_string.value
i18next::backendConnector: loading namespace myStrings for language en-US failed TypeError: Only absolute URLs are supported
这就是我的i18next配置(src/i18n/i18n.ts
)的样子:
import i18next from 'i18next';
import {initReactI18next} from 'react-i18next';
import httpApi from 'i18next-http-backend';
i18next
.use(initReactI18next)
.use(httpApi)
.init({
debug: process.env.NODE_ENV !== 'production',
lng: 'en-US',
ns: ['myStrings'],
fallbackNS: 'myStrings',
defaultNS: 'myStrings',
fallbackLng:'en-US',
preload: ['en-US', 'de-DE', 'es-ES'],
interpolation: {
prefix: "{{",
suffix: "}}"
},
load: "currentOnly",
supportedLngs: ['en-US', 'de-DE', 'es-ES'],
backend: {
loadPath: 'translations/{{ns}}-{{lng}}.json',
crossDomain: true
},
detection: {
order: ['cookie', 'htmlTag'],
},
react: {
useSuspense: false
},
});
export default i18next;
我就是这样访问它的(src/pages/localization.tsx
)的:
import React from "react";
import Head from "next/head";
import { NextPage } from "next";
import "../i18n/i18n";
import {Trans, useTranslation} from 'react-i18next';
const Home: NextPage = (props: any) => {
const { t, i18n } = useTranslation("myStrings");
return (
<div>
<Head>
<title>Home</title>
</Head>
<div>
<kat-flag size="small" country="us" onClick={() => i18n.changeLanguage("en-US")}> US </kat-flag>
<kat-flag size="small" country="de" onClick={() => i18n.changeLanguage("de-DE")}> DE </kat-flag>
<kat-flag size="small" country="es" onClick={() => i18n.changeLanguage("es-ES")}> ES </kat-flag>
<hr/>
<hr/>
<div> {t("resources.welcome_string.value")} </div>
</div>
</div>
);
};
export default Home;
在用localization.tsx
初始化i18next之前,我可能理解它正在加载代码i18next的错误。
我的问题是:
i18next.init
首先加载i18next-http-backend
,所以我的翻译字符串必须在public
文件夹中。我是否可以将翻译保存在非公用文件夹中(与src
和public
并行)并从那里加载。发布于 2021-05-14 21:11:20
i18next.init()
返回一个承诺,您可以简单地导出它并在代码中的某个地方等待它。或者,您可以通过i18next.on('initialized',()=>...)
建立一个侦听器。发布于 2021-05-16 19:42:02
Next.js也在服务器端执行,这意味着您的loadPath需要是绝对的,例如:https://my-domain.com/translations/{{ns}}-{{lng}}.json
https://stackoverflow.com/questions/67540800
复制相似问题