我有一个多语言的盖茨比网站,我试图提高灯塔的性能得分,所以我遵循this guide来生成带有html翻译的页面。这是我的gatsby-ssr.js
文件
import { renderToString } from 'react-dom/server'
import Backend from 'i18next-sync-fs-backend'
import i18n from "./src/locales/i18n"
const namespaces = [...my ns...];
export const replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
i18n
.use(Backend)
.init({
initImmediate: false,
backend: {
loadPath: 'src/locales/{{lng}}/{{ns}}.json',
},
})
// load the common namespace
.loadNamespaces(namespaces, (err) => {
replaceBodyHTMLString(renderToString(bodyComponent))
})
}
我的i18n.js
文件:
import i18n from "i18next";
import Backend from "i18next-xhr-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
i18n
.use(Backend)
.use(LanguageDetector)
.use(reactI18nextModule)
.init({
fallbackLng: "fr",
ns: ['translation'],
defaultNS: 'translation',
load: 'languageOnly',
debug: false,
interpolation: {
escapeValue: false, // not needed for react!!
},
react: {
wait: true,
},
});
export default i18n;
我在页面中使用react-i18next(v8)中的HOC withNamespaces
就像export default withNamespaces('home')(IndexPage);
这很好用,因为生成的HTML已翻译了所有文本,但是当我访问我的页面时,客户端将第二次加载翻译并重新渲染页面,这会导致页面闪烁和布局发生较大变化,因此灯塔真的不喜欢它。我相信这与i18next-xhr-backend
有关,但我被困住了。
我希望我的页面不会在页面加载时加载翻译,因为html已经翻译了文本,所以我不需要再次加载翻译