You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

next-i18next如何为所有页面加载通用本地化资源并合并?

在next-i18next中自动加载通用本地化资源并合并页面专属资源的方案

当然支持,不用自己封装工具就能实现这个需求。

Pages Router 实现方式

你可以在_app.js里通过getInitialProps获取页面本身的翻译资源,再将通用的footer、header资源合并进去,避免覆盖页面专属翻译:

import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import App from 'next/app';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

MyApp.getInitialProps = async (appContext) => {
  // 获取页面自身getInitialProps/getServerSideProps返回的props
  const appProps = await App.getInitialProps(appContext);
  const { locale } = appContext.router;

  // 加载通用翻译资源
  const commonTranslations = await serverSideTranslations(locale, ['footer', 'header']);
  
  // 合并页面已有翻译与通用资源
  const mergedProps = {
    ...appProps.pageProps,
    ...commonTranslations,
    // 重点合并_i18n中的namespaces,确保所有资源都被加载
    _i18n: {
      ...appProps.pageProps._i18n,
      ...commonTranslations._i18n,
      namespaces: [...(appProps.pageProps._i18n?.namespaces || []), ...commonTranslations._i18n.namespaces]
    }
  };

  return {
    ...appProps,
    pageProps: mergedProps
  };
};

export default MyApp;

之后每个页面只需要加载自身专属的翻译资源即可,比如:

export async function getServerSideProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['home']))
    }
  };
}

App Router(Next.js 13+)简化方案

如果用的是App Router,直接在根布局(layout.js)中加载通用翻译资源,页面组件加载自身专属资源即可。next-i18next会自动合并所有加载的namespaces,无需额外处理合并逻辑。

内容的提问来源于stack exchange,提问作者suben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:35:21