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、多语言、多个命名空间、多种翻译格式。

"next": "13.1.6",
"next-i18next": "^13.3.0"
"i18next": "^22.5.1",
"react-i18next": "^12.3.1",

开始设置next-i18next

安装相关依赖

pnpm add next-i18next react-i18next i18next

添加配置文件

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

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

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

/**
 * @type {import('next-i18next').UserConfig}
 */

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

在 next.config.ts 中引入文件

/** @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)

翻译内容

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

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

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

页面中使用翻译

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

import { appWithTranslation } from 'next-i18next'

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

export default appWithTranslation(MyApp)

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

// 页面级别组件中使用 
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 从而实现路由不带前缀就可以切换语言。

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

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 插件

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

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

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

{
  "i18n-ally.localesPaths": [
    "public/locales"
  ],
  "i18n-ally.keystyle": "nested"
}

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

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

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

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

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

内容推荐

原文链接:https://juejin.cn/post/7349791638112337930 作者:cv也要开心

(0)
上一篇 2024年3月28日 下午4:32
下一篇 2024年3月28日 下午4:42

相关推荐

发表回复

登录后才能评论