如何让next-i18next的common.json等文件全局无需SSR/SSG即可访问
让next-i18next的common/ui翻译文件全局可用(无需每个页面SSR/SSG调用)
要实现common.json、ui.json这类通用翻译文件在任意组件/路由全局可用,不用每个页面都在getStaticProps/getServerSideProps里重复引入,只需要两步配置:
1. 修改next-i18next配置文件
在next-i18next.config.js中添加默认命名空间和全局命名空间列表,把common、ui设为默认加载的通用命名空间:
/** @type {import('next-i18next').UserConfig} */ const i18nConfig = { i18n: { defaultLocale: 'en', locales: ['en', 'ckb', 'ar'] }, defaultNS: 'common', // 设置全局默认命名空间 ns: ['common', 'ui', 'home'] // 列出所有需要加载的命名空间 } module.exports = i18nConfig
2. 在自定义_app中注入全局翻译
Next.js的_app.tsx是所有页面的入口,在这里统一调用serverSideTranslations加载通用命名空间,所有页面就能自动继承这些翻译内容:
// src/pages/_app.tsx import type { AppProps } from 'next/app' import { appWithTranslation } from 'next-i18next' import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import type { GetStaticProps } from 'next' // 全局加载common和ui翻译 export const getStaticProps: GetStaticProps = async ({ locale }) => { return { props: { ...(await serverSideTranslations(locale as string, ['common', 'ui'])) } } } function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default appWithTranslation(MyApp)
3. 简化页面的getStaticProps
现在页面里只需要加载当前页面专属的翻译(比如home),不用再重复引入common和ui:
// src/pages/index.tsx export const getStaticProps: GetStaticProps = async ({ locale }) => { return { props: { ...(await serverSideTranslations(locale as string, ['home'])) // 仅加载页面专属命名空间 } } }
验证效果
现在不管是页面组件、全局公共组件(比如导航栏、页脚),甚至是404这类无对应路由的页面,都可以直接使用useTranslation调用common或ui里的翻译:
// 任意组件中使用通用翻译 import { useTranslation } from 'next-i18next' function Navbar() { const { t } = useTranslation('ui') return <nav>{t('navbar.title')}</nav> } export default Navbar
注意事项
- 确保
public/locales/[语言]/common.json和ui.json文件存在,否则会触发加载报错 - 动态路由页面同样不需要在
getStaticProps里重复引入通用命名空间 - 翻译文件会被缓存,修改后需要重启开发服务或重新构建生产环境
内容的提问来源于stack exchange,提问作者Rawand
相关产品推荐
相关产品推荐

