问题描述
在 /pages
中,我有 [page].js
和 index.js
。
[page].js
根据“CustomPage”的值生成需要的页面。它的内容来自 Data-JSON-File。
它按预期工作,只要我从主页开始并使用网页内的链接。 例如,我现在有 2 个页面:/impressum 和 /datenschutz。
所以点击链接“Impressum”打开myDomain.com/impressum
(它可以工作,但请注意,末尾没有.html)。
但是,如果我刷新页面,或者直接在浏览器的地址栏中输入 myDomain.com/impressum
,我会收到一个未找到的错误(来自 Nginx-server,而不是来自 next!)。 >
第二次尝试
因为我需要一个完全静态的页面,并且我在文件中添加了 getStaticPath
和 getStaticProps
用于测试目的,以便创建“真实”的 html 文件:
import { useRouter } from 'next/router';
import Index from './index';
import config from '../content/config.yml';
import CustomPage from '../src/components/CustomPage';
const RoutingPage = () => {
const { customPages } = config;
const router = useRouter();
const { page } = router.query;
const findMatches = (requestedPage) =>
customPages.find((customPage) => customPage.name === requestedPage) ||
false;
const customPageData = findMatches(page);
if (customPageData !== false) {
return <CustomPage pageContext={customPageData} />;
}
return page === 'index' ? (
<Index page={page} />
) : (
<p style={{ marginTop: '250px' }}>whats up {page}</p>
);
};
export async function getStaticPaths() {
return {
paths: [
{ params: { page: 'impressum' } },{ params: { page: 'datenschutz' } },],fallback: false,// See the "fallback" section below
};
}
export async function getStaticProps({ params }) {
return { props: { page: params.page } };
}
export default RoutingPage;
但这让我想到了下一个问题: 我在网页中实现了内部链接,如下所示:
仍将用户引导至 myDomain.com/impressum
,现在还有 myDomain.com/impressum.html
可用。从 SEO 的角度来看,这是两条不同的路径。
如何统一它们,以便我只有一条路径 - 无论是从网页中打开还是直接输入。
变通办法 (??)
当然,我可以在任何地方使用类似的东西:
<Link href={`/${item.page}.html`}>
但这只有在页面被导出并复制到服务器时才有效。对于 next dev
和 next start
这将不起作用,因为 .html-File 不存在......所以我会在页面上工作时丢失“页面预览”。
所以我唯一的想法是为 .env.development
和 .env.production
设置一个 ENV 变量,并将 NEXT 中的 -Component 封装在 HOC 中。
在该 HOC 中,我可以检查我当前是否在开发或生产中,并且不要将 .html 用于这些链接...否则将 .html 添加到链接中。
你对此有何看法。您还有其他解决方案吗?
解决方法
我不知道是不是 state of the art
,但我这样做的解决方法很少:
我将 next/link
-Component 放在 HOC 中并检查它是否在开发或生产中运行 (process.env.NODE_ENV):
import React from 'react';
import Link from 'next/link';
const LinkHoc = (props) => {
const { as,href,children } = props;
if (process.env.NODE_ENV === 'production') {
return (
<Link
{...props}
as={as ? `${as}.html` : ''}
href={href ? `${href}.html` : ''}
/>
);
}
return <Link {...props}>{children}</Link>;
};
export default LinkHoc;
通过这种变通方法,您可以在 DEV 中获得 mydomain.com/impressum
链接,在生产中获得 mydomain.com/impressum.html
。
至少要做的就是为生成的页面重命名 JSON 文件。
他们在/out/_next/data/XYZranadomString/
。
它们的名称类似于 impressum.json
,您需要将其重命名为 impressum.html.json
以修复客户端上此文件的 404 错误。