提问人:Josip Pardon 提问时间:11/15/2023 更新时间:11/16/2023 访问量:31
使用 i18next 库的更好方法 - 但我不知道如何实现它
Better approach for using i18next library - but I don't know how to achieve it
问:
我的问题在帖子的底部
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 的解决方案。
答:
0赞
hokwanhung
11/16/2023
#1
我会发布我的答案,只是为了吸引更好的想法。在 的 plugins 文档中,实际上有相当多的插件用于格式化翻译文件。i18next
可以提供帮助的插件是一个,它可以允许以下格式,尽管您仍然必须指定默认语言,但您可以执行以下操作: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
希望上面的答案会有所帮助。
评论