最详细的next国际化方案

实现效果 : 根据浏览器语言判断和手动切换(两种切换模式)

实现方法

1.下载安装包 (next-i18next react-i18next i18next)

yarn add next-i18next react-i18next i18next

2.在根目录下创建文件(next-i18next.config.js)  


const path = require("path");

module.exports = {
  i18n: {
    defaultLocale: "zh",
    locales: ["zh", "en"],
  },
  localePath: path.resolve("./public/locales"),
  shallowRender: true,
};

​

3.修改文件(next.config.js)

/** @type {import('next').NextConfig} */
const { i18n } = require('./next-i18next.config')
const nextConfig = {
  reactStrictMode: true,
  i18n,
}

module.exports = nextConfig

4.public目录下编写文本

5.pages目录下的_app.tsx文件修改

import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { appWithTranslation } from "next-i18next";
import nextI18NextConfig from "../../next-i18next.config";
function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default appWithTranslation(App, nextI18NextConfig);

6.页面中使用

import { useTranslation, I18nContext } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import nextI18NextConfig from "../../next-i18next.config.js";
import { useRouter } from "next/router.js";
import { Menu } from "antd";
export interface IndexProps {}

export default function Home(props: IndexProps) {
  const langs = {
    zh: "中国站",
    en: "Intl English",
  };
  const router = useRouter();
  const handleLanguageChange = (key: any) => {
    console.log(key);
    router.push(router.route, router.asPath, {
      locale: key,
    });
  };
  const { t } = useTranslation("common");

  return (
    <div>
      {t("nav.footer.solutions")}
      <Menu onClick={({ key }) => handleLanguageChange(key)}>
        {Object.keys(langs).map((key) => (
          <Menu.Item key={key}>{langs[key]}</Menu.Item>
        ))}
      </Menu>
    </div>
  );
}
export const getStaticProps = async ({ locale }: any) => ({
  props: {
    ...(await serverSideTranslations(locale, ["common"], nextI18NextConfig)),
  },
});

(但是注意react13以上并且用的是app路由的话最好是并采取这种方案i18n with Next.js 13 and app directory / App Router (an i18next guide))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值