Next.js next-i18next with next rewrite不适用于根页面重写路径
我们有一个现有的应用程序,默认情况下根Next.js next-i18next with next rewrite不适用于根页面重写路径,next.js,next-i18next,Next.js,Next I18next,我们有一个现有的应用程序,默认情况下根“/”被重定向到“/search”。通过我们的next redirects.js文件,它运行良好: async function redirects() { return [ { source: '/', destination: '/search', permanent: true, }, ]; } 我必须使用next-i18next实现对应用程序的翻译,这样我们就可以使用NextJS实现翻译文
“/”
被重定向到“/search”
。通过我们的next redirects.js
文件,它运行良好:
async function redirects() {
return [
{
source: '/',
destination: '/search',
permanent: true,
},
];
}
我必须使用next-i18next
实现对应用程序的翻译,这样我们就可以使用NextJS实现翻译文本+即时发送。我已经按照程序中的步骤进行了操作。我将next-i18next.config.js
文件添加为:
const path = require('path');
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'es'],
},
localePath: path.resolve('./public/static/locales'), // custom path file route
};
下一个.config如下所示:
const { i18n } = require('./next-i18next.config');
const defaultConfig = {
env: {
SOME_ENV,
},
images: {
deviceSizes: [980],
domains: [
'd1',
'd2',
],
},
i18n,
redirects: require('./next-redirects'),
webpack: (config, options) => {
if (!options.isServer) {
config.resolve.alias['@sentry/node'] = '@sentry/browser';
}
if (
NODE_ENV === 'production'
) {
config.plugins.push(
new SentryWebpackPlugin({
include: '.next',
ignore: ['node_modules'],
urlPrefix: '~/_next',
release: VERCEL_GITHUB_COMMIT_SHA,
})
);
}
return config;
},
};
module.exports = withPlugins([withSourceMaps], defaultConfig);
我们使用appWithTranslation
HOC包装了一个文件,并使用getInitialProps进行了设置,根据nextJS文档:
function MyApp({ Component, pageProps }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles);
}
TagManager.initialize(tagManagerArgs);
setMounted(true);
}, []);
const Layout = Component.Layout || Page;
return (
<>
<Head>
<link rel="icon" href="/favicon.png" type="image/ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<AppProviders>
<Context {...pageProps}>
<Layout {...pageProps}>
<>
<Component {...pageProps} />
<Feedback />
<PageLoader />
</>
</Layout>
</Context>
</AppProviders>
</>
);
}
MyApp.getInitialProps = async ({ Component, ctx }) => {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps({ ctx });
}
const cookies = Cookie.parse(ctx?.req?.headers?.cookie || '');
if (Object.keys(cookies).length) {
const { token } = JSON.parse(cookies?.user || '{}');
let user = null;
if (token) {
const { data } = await get('api/users', { token });
if (data) {
user = data;
user.token = token;
}
}
pageProps.user = user;
pageProps.cart = cookies?.cart;
pageProps.defaultBilling = cookies?.defaultBilling;
pageProps.reservationEstimateItem = cookies?.reservationEstimateItem;
pageProps.reservationEstimate = cookies?.reservationEstimate;
}
return { pageProps };
};
export default appWithTranslation(MyApp);
此时,重定向逻辑应继续导航到如下设置的搜索
页面:
export const SearchPage = () => {
const router = useRouter();
const { t } = useTranslation('search');
return (
<>
<Head>
<title>{`${t('searchTitle')}`}</title>
<meta
property="og:title"
content={`${t('searchTitle')}`}
key="title"
/>
<meta
name="description"
content={t('metaDescription')}
/>
</Head>
<Search />
</>
);
};
SearchPage.namespace = 'SearchPage';
export const getStaticPaths = () => ({
paths: [], // indicates that no page needs be created at build time
fallback: 'blocking' // indicates the type of fallback
});
export const getStaticProps = async ({ locale }) => ({
// exposes `_nextI18Next` as props which includes our namespaced files
props: {
...await serverSideTranslations(locale, ['common', 'search']),
}
});
export default SearchPage;
export const SearchPage=()=>{
const router=useRouter();
const{t}=usetransformation('search');
返回(
{`${t('searchTitle')}`}
);
};
SearchPage.namespace='SearchPage';
导出常量GetStaticPath=()=>({
路径:[],//表示在生成时不需要创建页面
回退:“阻塞”//表示回退的类型
});
export const getStaticProps=async({locale})=>({
//将“\u nextI18Next”作为道具公开,其中包括我们的命名空间文件
道具:{
…等待服务器端翻译(区域设置,['common',search']),
}
});
导出默认搜索页面;
根据next-i18next
,搜索页面具有所有页面级文件所需的getstaticpath
和getStaticProps
功能
为什么此设置不再适用于重定向
- 终端中没有错误
- 网络选项卡显示
的根路由上的
错误“/”404
- 如果我直接导航到
,它可以很好地加载,因此页面路径看起来还可以/search
- 下一步“^10.0.2”,
- next-i18next
“next-i18next”:“^7.0.1”,
- 删除原来的下一次重写
- 添加一个新的
页面文件,用于处理index.js
中的重定向:getServerSideProps
- 下一个地区似乎存在一些可能的问题(&L)。。。
我的解决方案并不漂亮,但它很有效:
你的
next.config.js
看起来像什么?更新了@juliomalvesreeved my answer…browserstack测试失败,没有重定向
export const SearchPage = () => {
const router = useRouter();
const { t } = useTranslation('search');
return (
<>
<Head>
<title>{`${t('searchTitle')}`}</title>
<meta
property="og:title"
content={`${t('searchTitle')}`}
key="title"
/>
<meta
name="description"
content={t('metaDescription')}
/>
</Head>
<Search />
</>
);
};
SearchPage.namespace = 'SearchPage';
export const getStaticPaths = () => ({
paths: [], // indicates that no page needs be created at build time
fallback: 'blocking' // indicates the type of fallback
});
export const getStaticProps = async ({ locale }) => ({
// exposes `_nextI18Next` as props which includes our namespaced files
props: {
...await serverSideTranslations(locale, ['common', 'search']),
}
});
export default SearchPage;
const Index = () => null;
export async function getServerSideProps({ locale }) {
return {
redirect: {
destination: `${locale !== 'en' ? `/${locale}` : ''}/search`,
permanent: true,
},
};
}
export default Index;