getStaticPath 和 URL 中文件类型的需要

问题描述

/pages 中,我有 [page].jsindex.js

[page].js 根据“CustomPage”的值生成需要的页面。它的内容来自 Data-JSON-File。

它按预期工作,只要我从主页开始并使用网页内的链接。 例如,我现在有 2 个页面:/impressum 和 /datenschutz。

所以点击链接“Impressum”打开myDomain.com/impressum(它可以工作,但请注意,末尾没有.html)。 但是,如果我刷新页面,或者直接在浏览器的地址栏中输入 myDomain.com/impressum,我会收到一个未找到的错误(来自 nginx-server,而不是来自 next!)。 >

第二次尝试

因为我需要一个完全静态的页面,并且我在文件中添加了 getStaticPathgetStaticProps 用于测试目的,以便创建“真实”的 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;

这会将单个页面生成为真正的 html 文件:

enter image description here

但这让我想到了下一个问题: 我在网页中实现了内部链接,如下所示:

enter image description here

仍将用户引导至 myDomain.com/impressum,现在还有 myDomain.com/impressum.html 可用。从 SEO 的角度来看,这是两条不同的路径。

如何统一它们,以便我只有一条路径 - 无论是从网页中打开还是直接输入。

变通办法 (??)

当然,我可以在任何地方使用类似的东西:

<Link href={`/${item.page}.html`}>

但这只有在页面被导出并复制到服务器时才有效。对于 next devnext start 这将不起作用,因为 .html-File 不存在......所以我会在页面上工作时丢失“页面预览”。

所以我唯一的想法是为 .env.development.env.production 设置一个 ENV 变量,并将 NEXT 中的 -Component 封装在 HOC 中。 在该 HOC 中,我可以检查我当前是否在开发或生产中,并且不要将 .html 用于这些链接...否则将 .html 添加到链接中。

对此有何看法。您还有其他解决方案吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)