我的问题在帖子底部
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import { Provider } from "react-redux";
// Bootstrap CSS
import "bootstrap/dist/css/bootstrap.min.css";
// Bootstrap Bundle JS
import "bootstrap/dist/js/bootstrap.bundle.min";
import "./styles/index.scss";
import { store } from "./store/store.ts";
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import HttpApi from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { Suspense } from "react";
i18next
.use(HttpApi)
.use(LanguageDetector)
.use(initReactI18next)
.init({
supportedLngs: ["en", "hr"],
fallbackLng: "en",
debug: false,
backend: {
loadPath: "/locales/{{lng}}/translation.json",
},
});
const loadingMarkup = (
<div className="py-4 text-center">
<h3>Loading..</h3>
</div>
);
ReactDOM.createRoot(document.getElementById("root")!).render(
<Provider store={store}>
<Suspense fallback={loadingMarkup}>
{/* EVERYTHING WILL BE LOADED ONLY AFTER LANGUAGE JSON IS FETCHED
you can now use translations in components without fear */}
<App />
</Suspense>
</Provider>
);
这假设我在公共文件夹中拥有每种语言的 json 文件:
public/locales/en/translation.json:
{
"welcome_message": "Welcome to the app"
"go_back": "Go back"
}
public/locales/de/translation.json:
{
"welcome_message": "Willkommen in der App"
"go_back": "Geh zurück"
}
但我想要一个主要的 json 文件,其中包含每种语言的翻译,如下所示:
public/locales/translations.json:
{
"welcome_message": {
"en": "Welcome to the app",
"de": "Willkommen in der App"
}
"go_back": {
"en": "Go back",
"de": "Geh zurück"
}
}
当浏览器请求特定语言时,此主文件用于生成该语言的 json 文件。例如,如果请求“en”,则返回的文件为:
{
"welcome_message": "Welcome to the app!",
"go_back": "Go back"
}
我提出的方法更有条理且不易出错。我非常沮丧,因为这不是 i18next 的默认工作方式。有可能以某种方式实现它吗?
我找不到任何讨论此问题的资源。人工智能聊天机器人也毫无用处。我认为可以通过将翻译文件存储在某个单独的服务器(例如 Node + Express)上并从中请求 json 来非常轻松地做到这一点,但我想要仅使用 React 的解决方案。
我发布我的答案只是为了吸引更好的想法。在
i18next
的插件文档中,实际上有很多用于格式化JSON
文件的插件。
就
i18next-shopify
而言,它可以允许以下格式,尽管您仍然必须指定默认语言,但您可以执行以下操作:
import i18next from "i18next";
import ShopifyFormat from "@shopify/i18next-shopify";
i18next.use(ShopifyFormat).init({
lng: "en",
resources: {
en: {
translation: {
welcome_message: {
"en": "Welcome to the app",
"de": "Willkommen in der App",
},
go_back: {
"en": "Go back!",
"de": "Geh zurück",
},
},
}
}
});
i18next.t("welcome_message.en"); // -> Welcome to the app
i18next.t("go_back.de"); // -> Geh zurück
但是,我想说,即使这个解决方案可行,它也是一个需要额外步骤的解决方案,并且
react-i18next
(还有i18next
)总是更喜欢./locales/{language}/{namespace}.json
的格式。
将翻译文件与语言分开只是一种常见做法,如果您想澄清文件的结构,可以使用
namespace
作为 principles 建议。
希望以上回答对您有帮助。