当前位置:   article > 正文

最详细的next国际化方案_nextjs 国际化

nextjs 国际化

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

实现方法

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))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/913660
推荐阅读
相关标签
  

闽ICP备14008679号