Next.js TS项目中如何自定义next-i18next的JSON语言文件结构?
解决next-i18next读取根级语言文件的配置方案
要让next-i18next直接读取public/locales/en.json、public/locales/fr.json这类根级语言文件,而非默认的{{lng}}/{{ns}}.json结构,只需修改next-i18next.config.mjs文件,调整命名空间和加载路径配置:
修改后的完整配置文件
import path from 'path'; const nextI18NextConfig = { debug: process.env.NODE_ENV === 'development', i18n: { defaultLocale: 'en', locales: ['en', 'fr'], // 可按需添加更多语言 }, // 指定默认命名空间(可自定义名称,这里用translation作为示例) defaultNS: 'translation', // 声明使用的命名空间列表 ns: ['translation'], // 自定义语言文件加载路径,直接指向{{lng}}.json loadPath: typeof window === 'undefined' ? path.resolve('./public/locales/{{lng}}.json') : '/locales/{{lng}}.json', fallbackLng: 'en', interpolation: { escapeValue: false, // React环境无需转义 }, }; export default nextI18NextConfig;
关键配置说明
defaultNS:设置默认使用的命名空间,对应语言文件中的顶级键值对集合ns:声明项目中使用的所有命名空间列表,这里仅需一个对应根级文件的命名空间loadPath:覆盖默认的文件加载路径模板,直接指向{{lng}}.json,而非{{lng}}/{{ns}}.json
语言文件示例
你的public/locales/en.json内容可以是:
{ "hello": "Hello", "welcome": "Welcome to the app" }
public/locales/fr.json内容:
{ "hello": "Bonjour", "welcome": "Bienvenue dans l'application" }
组件中使用示例
import { useTranslation } from 'next-i18next'; export default function Home() { const { t } = useTranslation(); return ( <div> <h1>{t('hello')}</h1> <p>{t('welcome')}</p> </div> ); }
内容的提问来源于stack exchange,提问作者Tanuj0610
相关产品推荐
相关产品推荐

