NextJS多语言

NextJS多语言

前面的步骤AI辅助下完成,但是会有些坑,记录一下

step1 : 首先,安装next-intl

shell 复制代码
npm install next-intl

step2 : 在 /src/app 目录下创建一个 locale 文件夹

step3: 创建一个 messages 文件夹(在==/src== 目录下),用于存储不同语言的翻译文件。例如:

json 复制代码
{
  "Index": {
    "title": "Welcome to our app",
    "editFile": "Edit this file to get started"
  }
}

en.json

json 复制代码
{
  "Index": {
    "title": "你好",
    "editFile": "是的"
  }
}

zh.json **step4**: 在 /src/app 目录下创建一个 i18n.js 文件:

js 复制代码
import {getRequestConfig} from 'next-intl/server';
 
export default getRequestConfig(async ({locale}) => ({
  messages: (await import(`../messages/${locale}.json`)).default
}));

// -------人工修正后----------------,locale参数被弃用,会一直warn
import {getRequestConfig} from 'next-intl/server';

export default getRequestConfig(async ({requestLocale}) => {
  // 等待 Promise 解析以获取实际的 locale 值
  const locale = await requestLocale;
  // console.log('getRequestConfig', locale);
  
  return {
    messages: (await import(`../messages/${locale}.json`)).default
  };
});

step5: 修改 next.config.mjs 文件以配置支持的语言:

js 复制代码
import createNextIntlPlugin from 'next-intl/plugin';

const withNextIntl = createNextIntlPlugin('./src/app/i18n.js');

/** @type {import('next').NextConfig} */
const nextConfig = {};

export default withNextIntl(nextConfig);

step6 : 需要在 /src/ 目录下创建一个 middleware.js 文件来处理语言切换:

js 复制代码
import createMiddleware from 'next-intl/middleware';
import { NextResponse } from 'next/server';

const intlMiddleware = createMiddleware({
  locales: ['en', 'zh'],
  defaultLocale: 'en'
});
// -----有一些调试信息--------------
export default function middleware(request) {
  console.log('Middleware is running for path:', request.nextUrl.pathname);
  
  const response = intlMiddleware(request);
  
  // 检查是否有重定向
  if (response instanceof NextResponse && response.headers.has('Location')) {
    console.log('Redirecting to:', response.headers.get('Location'));
  } else {
    // 如果没有重定向,尝试推断目标文件夹
    const locale = request.nextUrl.pathname.split('/')[1] || 'en';
    console.log('Likely targeting folder:', `/src/app/${locale}`);
  }

  return response;
}

export const config = {
  matcher: ['/((?!api|_next|.*\\..*).*)', '/', '/(zh|en)/:path*']
};

前面六步是ai的辅助下确定的步骤,标红的是我当时容易混淆的。后面一直报错,接近耗时3h解决

  • 自己对nextjs不熟悉
  • 使用的版本较新 next 15.0.3 next-intl 3.25.3

最烧脑的 for me,是layout.js、page.js,这两个文件我有点泠不太清

把脚手架创建的layout.js page.js移动到locale文件夹下

内容如下:

js 复制代码
export default async function RootLayout({ children , params  }) {
  const {locale} = await params;
  console.log("layoutjs", locale);
  return (
    <html lang={locale}>
      <body>
        layout js
        {children}
      </body>
    </html>
  );
}

layout.js

  • 去locale值需要异步,这是版本更新,可能AI给的回复不是
js 复制代码
import { useTranslations } from 'next-intl';

export default function Home() {
  const t = useTranslations('Index');
  console.log(t('title'));
  return (
    <div>
      page js
      <h1>{t('title')}</h1>
    </div>
  );
}

page.js

  • 这里没有问题,但是AI给的i18n.js的版本比较老,会warn
相关推荐
小林ixn7 分钟前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker33 分钟前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜1 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康1 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端
一点一木2 小时前
从60首歌到1个网站:输入你的故事,还你一首歌
前端·github
IT_陈寒3 小时前
Vue这个特性差点让我加班到凌晨,谁懂啊
前端·人工智能·后端
kyriewen3 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
遇乐的果园4 小时前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
用户985033593284 小时前
OpenLayers 热力图从原理到 Vue 组件一键接入
前端
颜酱4 小时前
01 | 骨架搭建:FastAPI + Vue 跑通第一个 SSE 流式问答
前端·人工智能·后端