如何在NextJS的_document文件<Head>中使用next-i18next实现翻译?
用next-i18next为NextJS的_document或_app添加meta标签翻译支持
可以实现meta标签的翻译支持,不过由于_document是服务端渲染的根组件,无法直接使用next-i18next的useTranslation钩子,需要通过两种不同的方案处理:
方案一:在_document中手动加载翻译资源
_document的getInitialProps是服务器端唯一能执行异步逻辑的地方,我们可以在这里创建i18n实例、加载对应语言的翻译资源,再将翻译后的内容传递给组件使用:
// pages/_document.js import Document, { Html, Head, Main, NextScript } from 'next/document'; import { createInstance } from 'i18next'; import resourcesToBackend from 'i18next-resources-to-backend'; import { i18nConfig } from '../i18n.config'; // 你的i18n配置文件 class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); // 获取当前请求的语言(优先从请求头取, fallback到默认语言) const locale = ctx.req?.headers['accept-language']?.split(',')[0] || i18nConfig.defaultLocale; // 创建i18n实例并加载目标语言的翻译资源 const i18nInstance = createInstance(); await i18nInstance .use(resourcesToBackend((language, namespace) => import(`../public/locales/${language}/${namespace}.json`))) .init({ ...i18nConfig, lng: locale, interpolation: { escapeValue: false } // NextJS的meta标签不需要转义 }); // 翻译meta内容 const translatedDescription = i18nInstance.t('header:description'); return { ...initialProps, translatedDescription, locale }; } render() { return ( <Html lang={this.props.locale}> <Head> <meta name="description" content={this.props.translatedDescription} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
方案二:在_app中管理meta标签(更推荐)
由于_app是所有页面的父组件,能直接通过next-i18next的useTranslation钩子获取翻译上下文,这种方式更符合next-i18next的常规使用流程,且客户端导航时meta标签会自动更新:
// pages/_app.js import { AppProps } from 'next/app'; import { useTranslation } from 'next-i18next'; import { appWithTranslation } from 'next-i18next'; import Head from 'next/head'; function MyApp({ Component, pageProps }: AppProps) { const { t } = useTranslation('header'); return ( <> <Head> <meta name="description" content={t('description')} /> </Head> <Component {...pageProps} /> </> ); } export default appWithTranslation(MyApp);
方案对比
- 方案一适合必须在
_document中添加meta标签的场景,但需要手动处理服务器端的资源加载,客户端导航时不会自动更新meta内容,需额外处理。 - 方案二更简洁,利用next-i18next的现有逻辑,自动处理服务端/客户端的翻译同步,是更推荐的实现方式。
内容的提问来源于stack exchange,提问作者Aleksandrs
相关产品推荐
相关产品推荐

