You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Next.js 13.4.1 App目录集成next-translate-plugin实现多语言切换失败排查求助

Next.js 13.4.1 App目录集成next-translate-plugin实现多语言切换失败排查求助

嘿Inti,我完全懂你现在这种挫败感——跟着一堆教程一步步走,结果多语言功能还是没动静,这种摸不着头脑的感觉真的糟透了!咱们一起来梳理下你的代码,揪出那些可能被忽略的小问题,把这个多语言功能搞定!

先从配置文件的细节开始排查

1. next.config.js的配置冲突问题

你在next.config.js里手动加了i18n配置,但next-translate-plugin会自动读取i18n.js的配置,手动添加的i18n反而会导致冲突。把它改成这样:

const nextTranslate = require('next-translate-plugin')

module.exports = nextTranslate({
  reactStrictMode: true,
})

2. i18n.js里的致命空格!

我注意到你在i18n.js里写了'/': [ 'home ']——home后面多了一个空格!这个小细节会让next-translate找不到对应的翻译文件,赶紧改成:

module.exports = {
  locales: ['en','es'],
  pages: {
    '*': ['common'],
    '/': ['home'],
    '/resume': ['resume'],
    '/property': ['property'],
    '/crypto': ['crypto']
  },
}

翻译文件目录结构要规范

确保你的locales目录结构完全匹配配置:

locales/
  en/
    common.json
    home.json
    resume.json
    property.json
    crypto.json
  es/
    common.json
    home.json
    resume.json
    property.json
    crypto.json

每个页面对应的翻译文件都要存在,且文件名和i18n.js里配置的一致。

App Router下的多语言切换实现

你还没加语言切换按钮,这里给你一个简单的客户端组件示例,直接加到你的页面里就行:

"use client"
import useTranslation from 'next-translate/useTranslation';
import { useRouter } from 'next/navigation';

const LanguageSwitcher = () => {
  const { lang } = useTranslation('common');
  const router = useRouter();

  const switchLang = (newLang) => {
    // 替换当前路径的语言前缀
    const currentPath = window.location.pathname;
    const newPath = currentPath.startsWith(`/${lang}`) 
      ? currentPath.replace(`/${lang}`, `/${newLang}`) 
      : `/${newLang}${currentPath}`;
    router.push(newPath);
  };

  return (
    <button 
      onClick={() => switchLang(lang === 'es' ? 'en' : 'es')}
      className="ml-2 px-3 py-1 rounded bg-emerald-400 text-gray-900"
    >
      {lang === 'es' ? 'English' : 'Español'}
    </button>
  );
};

export default LanguageSwitcher;

最后别忘了清缓存重启

有时候Next.js的缓存会让修改不生效,执行以下命令彻底清理后重启开发服务器:

rm -rf .next
npm run dev

按照上面的步骤一步步排查,应该就能解决问题了!如果还有其他小细节卡住,随时再梳理~

备注:内容来源于stack exchange,提问作者Inti

火山引擎 最新活动