Next.js: 如何从 getStaticProps 中获取静态资源

Next.js: How to get static assets from within getStaticProps

我正在使用 Netlify CMS。我想将轮播的所有幻灯片导入我的组件。我制作了一个名为滑块的集合并添加了一些幻灯片。这在 public/content/slider/ 中创建了两个降价文件(每张幻灯片一个)。我想将它们全部导入到一个可迭代对象中,以便我可以构建轮播。

因为我有一个为 markdown 文件设置的 webpack 加载器,我可以导入单个 markdown 文件没问题,像这样:

import post from '../public/content/posts/[post name].md

但是当我尝试使用 require.context, require-context 或导入 fs 时,它并不好。所以我决定尝试从 getStaticProps 中获取这些库。但是 getStaticProps 中的 __dirname/,我计算机文件系统的根目录。

所有 getStaticProps 示例都使用数据获取。我缺少一些信息。如何导入 /slides/ 文件夹中的所有 markdown 文件?

这是 known issue in Next.js__dirname 错误地解析为 / - 您应该改用 process.cwd()

来自 Next.js Reading files 文档:

Files can be read directly from the filesystem in getStaticProps.

In order to do so you have to get the full path to a file.

Since Next.js compiles your code into a separate directory you can't use __dirname as the path it will return will be different from the pages directory.

Instead you can use process.cwd() which gives you the directory where Next.js is being executed.