Next.js国际化多语言探索实践

Next.js国际化多语言探索实践

Next.js框架为我们提供了一个强大且易于使用的解决方案来实现网站的国际化(i18n)。Next.js的国际化特性允许我们轻松地为我们的网站添加多种语言支持,并且可以自动根据用户的语言偏好来显示相应的页面。

i18n 路由支持目前旨在补充现有的 i18n 库解决方案,例如react-intl,react-i18next,lingui,rosetta,next-intl,next-translate,next-multilingual,tolgee,以及其他通过简化路线和区域设置解析。

如果你已经掌握了国际化的能力,本文还有几个关键点。

  • Next.js 国际化如何去掉语言的路由前缀 /en /zh /fr
  • docker 部署的注意事项,output: 'standalone' 模式
  • vscode i18n-ally 插件

项目背景

首先文章是适用于 next(page router)的解决方案。使用next-i18next,它支持 SSR、多语言、多个命名空间、多种翻译格式。

json 复制代码
"next": "13.1.6",
"next-i18next": "^13.3.0"
"i18next": "^22.5.1",
"react-i18next": "^12.3.1",

开始设置next-i18next

安装相关依赖

csharp 复制代码
pnpm add next-i18next react-i18next i18next

添加配置文件

首先,在项目的根目录中创建一个文件next-i18next.config.js。其中localeDetection: false

这个属性当localeDetection设置为falseNext.js 将不再根据用户的首选区域设置自动重定向,并且仅提供从基于区域设置的域或区域设置路径检测到的区域设置信息。

这样就可以避免路由中出现语言前缀,但是切换语言需要我们自己手动处理。在后面~~~

java 复制代码
/**
 * @type {import('next-i18next').UserConfig}
 */

module.exports = {
  i18n: {
    defaultLocale: 'zh',
    locales: ['en', 'zh'],
    localeDetection: false
  }
};

next.config.ts 中引入文件

javascript 复制代码
/** @type {import('next').NextConfig} */
const { i18n } = require('./next-i18next.config')

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})

const nextConfig = {
  i18n,
  output: 'standalone',
  reactStrictMode: false,
  compress: true,
}

module.exports = withBundleAnalyzer(nextConfig)

翻译内容

一般的翻译结构像这样,支持嵌套,直接传递一个变量

页面中使用翻译

首先使用appWithTranslation HOC 包裹 App 组件,HOCappWithTranslation主要负责添加I18nextProvider

javascript 复制代码
import { appWithTranslation } from 'next-i18next'

const MyApp = ({ Component, pageProps }) => (
  <Component {...pageProps} />
)

export default appWithTranslation(MyApp)

页面级别的组件 中使用 getStaticProps 或者getServerSideProps

typescript 复制代码
// 页面级别组件中使用 
export async function getServerSideProps(content: any) {
  const instanceName = content?.query?.instanceName || '';
  return {
    props: {
      instanceName,
      ...(await serviceSideProps(content))
    }
  };
}

// 封装的 serviceSideProps 方法
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { LANG_KEY } from './cookieUtils';

export const serviceSideProps = (content: any) => {
  return serverSideTranslations(
    content.req.cookies[LANG_KEY] || 'zh',
    undefined,
    null,
    content.locales
  );
};

请注意,serverSideTranslations必须从以下位置导入next-i18next/serverSideTranslations------这是一个包含 NodeJs 特定代码的单独模块。

serverSideTranslations主要负责将翻译和配置选项作为 props 传递到页面中 - 您需要将其添加到任何具有翻译的页面。

Next.js 国际化如何去掉语言的路由前缀

首先是 next-i18next.config.js 配置 localeDetection: false ,Next.js 支持使用 NEXT_LOCALE cookie 覆盖 accept-language header

例如,如果用户更喜欢fr其接受语言标头中的区域设置,但NEXT_LOCALE=en设置了 cookie,en则访问/用户时的区域设置将被重定向到en区域设置位置,直到 cookie 被删除或过期。我们自己去管理这个 cookie 从而实现路由不带前缀就可以切换语言。

typescript 复制代码
import Cookies from 'js-cookie';

export const LANG_KEY = 'NEXT_LOCALE';

export const setLangStore = (value: string) => {
  return Cookies.set(LANG_KEY, value, { expires: 30, sameSite: 'None', secure: true });
};

export const getLangStore = () => {
  return Cookies.get(LANG_KEY);
};

export const removeLangStore = () => {
  Cookies.remove(LANG_KEY);
};

Docker部署的注意事项

docker 部署的情况,也就是 Next.js 的打包模式为 output: 'standalone'

Dockerfile请不要忘记将和复制到 Docker 映像中。next.config.jsnext-i18next.config.js

python 复制代码
COPY --from=builder /app/next.config.js ./next.config.js
COPY --from=builder /app/next-i18next.config.js ./next-i18next.config.js

Vscode i18n-ally 插件

能够大大提高我们的翻译效率,看到翻译进度和哪里内容缺失翻译。

在项目根目录,添加一个插件的设置.vscode settings.json

json 复制代码
{
  "i18n-ally.localesPaths": [
    "public/locales"
  ],
  "i18n-ally.keystyle": "nested"
}

当鼠标点击的时候,你可以轻松的看到翻译的内容,如下图

还有一个beta的功能,Possible Hard string 都不需要自己去写 t() {t('There is no resource of this type')}

内容推荐

相关推荐
昨天;明天。今天。3 分钟前
案例-任务清单
前端·javascript·css
zqx_71 小时前
随记 前端框架React的初步认识
前端·react.js·前端框架
惜.己2 小时前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
什么鬼昵称2 小时前
Pikachu-csrf-CSRF(get)
前端·csrf
长天一色2 小时前
【ECMAScript 从入门到进阶教程】第三部分:高级主题(高级函数与范式,元编程,正则表达式,性能优化)
服务器·开发语言·前端·javascript·性能优化·ecmascript
NiNg_1_2342 小时前
npm、yarn、pnpm之间的区别
前端·npm·node.js
秋殇与星河3 小时前
CSS总结
前端·css
BigYe程普3 小时前
我开发了一个出海全栈SaaS工具,还写了一套全栈开发教程
开发语言·前端·chrome·chatgpt·reactjs·个人开发
余生H3 小时前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
程序员-珍3 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发