Next.js部署Vercel/Netlify调用serverSideTranslations找不到翻译文件
问题根因
你使用的Next.js 11 + next-i18next 8.x版本存在两个核心问题:一是localePath配置错误,指向了不存在的根目录locales路径;二是Serverless部署环境下,默认不会将public/locales下的翻译文件打包到云函数的执行目录,导致serverSideTranslations执行时扫描路径失败。
解决方案
按以下步骤修改配置即可:
- 修正
next-i18next.config.js配置localePath配置必须放在根级,不要放在i18n子对象中,同时调整路径适配Serverless环境:
const path = require('path'); module.exports = { i18n: { defaultLocale: 'he', locales: ['he'], }, keySeparator: '>', nsSeparator: '|', reloadOnPrerender: false, localePath: typeof window === 'undefined' ? path.resolve('./public/locales') : '/locales', };
- 修正
next.config.js配置
添加unstable_includeFiles配置,明确要求Serverless打包时包含翻译文件:
const path = require('path'); const { PHASE_DEVELOPMENT_SERVER } = require('next/constants') const i18NextConfig = require('./next-i18next.config'); const prodConfig = { generateBuildId: () => 'build-id', compress: true, target: 'serverless', i18n: i18NextConfig.i18n, sassOptions: { includePaths: [path.join(__dirname, 'styles')], }, // 新增以下配置 unstable_includeFiles: [ 'public/locales/**/*', ], } module.exports = (phase, { defaultConfig }) => { if (phase === PHASE_DEVELOPMENT_SERVER) { return { ...defaultConfig, ...prodConfig, compress: false, } } return prodConfig; }
- 确认项目目录结构
确保翻译文件存放路径正确,结构如下:
项目根目录 └── public └── locales └── he ├── common.json └── 其他翻译文件.json
- 显式指定调用时的命名空间
调用serverSideTranslations时主动传入当前页面用到的翻译命名空间,避免自动扫描:
export async function getStaticProps({ locale }) { return { props: { ...(await serverSideTranslations(locale, ['common', 'home'])), }, } }
修改完成后重新部署即可解决报错。
内容的提问来源于stack exchange,提问作者Nadav Avisror
相关产品推荐
相关产品推荐

