• 最详细的next国际化方案


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

    实现方法

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

    yarn add next-i18next react-i18next i18next

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

    1. const path = require("path");
    2. module.exports = {
    3. i18n: {
    4. defaultLocale: "zh",
    5. locales: ["zh", "en"],
    6. },
    7. localePath: path.resolve("./public/locales"),
    8. shallowRender: true,
    9. };

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

    1. /** @type {import('next').NextConfig} */
    2. const { i18n } = require('./next-i18next.config')
    3. const nextConfig = {
    4. reactStrictMode: true,
    5. i18n,
    6. }
    7. module.exports = nextConfig

    4.public目录下编写文本

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

    1. import "@/styles/globals.css";
    2. import type { AppProps } from "next/app";
    3. import { appWithTranslation } from "next-i18next";
    4. import nextI18NextConfig from "../../next-i18next.config";
    5. function App({ Component, pageProps }: AppProps) {
    6. return <Component {...pageProps} />;
    7. }
    8. export default appWithTranslation(App, nextI18NextConfig);

    6.页面中使用

    1. import { useTranslation, I18nContext } from "next-i18next";
    2. import { serverSideTranslations } from "next-i18next/serverSideTranslations";
    3. import nextI18NextConfig from "../../next-i18next.config.js";
    4. import { useRouter } from "next/router.js";
    5. import { Menu } from "antd";
    6. export interface IndexProps {}
    7. export default function Home(props: IndexProps) {
    8. const langs = {
    9. zh: "中国站",
    10. en: "Intl English",
    11. };
    12. const router = useRouter();
    13. const handleLanguageChange = (key: any) => {
    14. console.log(key);
    15. router.push(router.route, router.asPath, {
    16. locale: key,
    17. });
    18. };
    19. const { t } = useTranslation("common");
    20. return (
    21. <div>
    22. {t("nav.footer.solutions")}
    23. <Menu onClick={({ key }) => handleLanguageChange(key)}>
    24. {Object.keys(langs).map((key) => (
    25. <Menu.Item key={key}>{langs[key]}Menu.Item>
    26. ))}
    27. Menu>
    28. div>
    29. );
    30. }
    31. export const getStaticProps = async ({ locale }: any) => ({
    32. props: {
    33. ...(await serverSideTranslations(locale, ["common"], nextI18NextConfig)),
    34. },
    35. });

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

  • 相关阅读:
    AI推介-多模态视觉语言模型VLMs论文速览(arXiv方向):2024.03.01-2024.03.05
    pyqt环境搭建
    linux安装部署lua环境
    Mybatis 缓存原理
    《精通Spring4.x 企业应用开发实战》
    NodeJS开发环境搭建
    初始环境配置
    常用排序算法实现
    数学建模文写作----个人笔记
    利用websocket仿web端在线客服实时聊天系统
  • 原文地址:https://blog.csdn.net/m0_66809099/article/details/133301246