使用 next.js 以编程方式为静态页面创建链接

Programmatically creating links for static pages with next.js

对于包含一堆静态页面(不是动态路由!)的 next.js 页面目录…

pages/
├── index.tsx
├── SomePage.tsx
├── someOtherPage
│   └── index.tsx
├── someOtherOtherPage
│   └── index.tsx
└── someOtherOtherOtherPage
    └── index.tsx

…是否可以在构建时创建链接,而不是手动输入所有内容?

即:不是这个:

// index.js
<ol>
  <li>
    <Link href="/somePage/">Some Page</Link>
  </li>
  <li>
    <Link href="/someOtherPage/">Some Other Page</Link>
  </li>
  …
</ol>

…但与 Gatsby's approach 相当的东西使用 Graphql 节点作为位置道具:

// Example Gatsby.js page

const IndexPage = ({
  data: {
    allMarkdownRemark: { edges },
  },
}) => {
  const Posts = edges
    .filter(edge => !!edge.node.frontmatter.date) // You can filter your posts based on some criteria
    .map(edge => <PostLink key={edge.node.id} post={edge.node} />)

  return <div>{Posts}</div>
}

我认为唯一的方法是在构建时使用 fsprocess.cwd()getStaticProps 中读取文件。
像这样:

import { promises as fs } from 'fs'
import path from 'path'

const Test= ({ urls }) => {
    return (
        <ul>
            {
                urls.map(el => <li key={el}>{el}</li>)
            }
        </ul>
    )
}

export async function getStaticProps() {
    const postsDirectory = path.join(process.cwd(), '/pages')
    const filenames = await fs.readdir(postsDirectory)
    return {
        props: {
            urls: filenames,
        },
    }
}

export default Test

您还可以将页面信息(例如路径和名称)存储在数据库中,然后查询数据库。