1

我试图通过在next-i18next包中更改站点的子路径来找到一种更改语言的方法,我搜索了Internethttps://github.com/isaachinman/next-i18next/issues/32,https:/ /github.com/i18next/i18next-browser-languageDetector#detector-options)来回答这个问题,但它没有用。更改 url 中的子路径后,它被复制并将我重定向到一个不存在的页面。

在此处输入图像描述

我的代码:

// path-to-my-project/i18n.js
const NextI18Next = require('next-i18next').default;
const i18nextBrowserLanguageDetector = require('i18next-browser-languagedetector').default;
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig;
const path = require('path');

module.exports = new NextI18Next({
    otherLanguages: ['ru'],
    defaultNS: 'common',
    localeSubpaths,
    localePath: path.resolve('./public/static/locales'),
    use: [i18nextBrowserLanguageDetector],
});
// path-to-my-project/pages/_app.js
import '../styles/main.scss';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import Router from 'next/router';
import App from 'next/app';
import { appWithTranslation } from '../i18n';

Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());

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

MyApp.getInitialProps = async (appContext) => ({ ...await App.getInitialProps(appContext) });

export default appWithTranslation(MyApp);

也许我只是错过了一些东西,因为这是我在 next.js 上的第一个项目,所以我在社区中寻求帮助,如果有任何帮助或提示,我将不胜感激。

4

2 回答 2

2

默认情况下next-i18next会尝试检测用户浏览器显示的语言。

尝试禁用它。

const NextI18Next = require('next-i18next').default
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig
const path = require('path')

module.exports = new NextI18Next({
  browserLanguageDetection: false, // <---
  serverLanguageDetection: false, // <---
  otherLanguages: ['de'],
  localeSubpaths,
  localePath: path.resolve('./public/static/locales')
})
于 2020-09-28T10:10:25.580 回答
1

在文件 next.config.js 我有这个设置:

// path/to/project/next.config.js

const { nextI18NextRewrites } = require('next-i18next/rewrites');

const localeSubpaths = {
    ru: 'ru',
};

module.exports = {
    rewrites: async () => nextI18NextRewrites(localeSubpaths),
    publicRuntimeConfig: {
        localeSubpaths,
    },
    devIndicators: {
        autoPrerender: false,
    },
};

但是没有足够的英文本地化配置,所以你只需要添加它:

// path/to/project/next.config.js

const { nextI18NextRewrites } = require('next-i18next/rewrites');

const localeSubpaths = {
    en: 'en', // <------
    ru: 'ru',
};

module.exports = {
    rewrites: async () => nextI18NextRewrites(localeSubpaths),
    publicRuntimeConfig: {
        localeSubpaths,
    },
    devIndicators: {
        autoPrerender: false,
    },
};

于 2020-09-30T10:52:47.793 回答