通过网址路径确定语言

问题描述

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

enter image description here

我的代码

// 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上的第一个项目,所以我在社区中寻求帮助,感谢您的帮助或提示

解决方法

默认情况下,next-i18next会尝试检测要从users browser显示的语言。

尝试将其禁用。

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')
})
,

在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',};