Next.js:如何从 getStaticProps 中获取静态资产 [英] Next.js: How to get static assets from within getStaticProps

查看:73
本文介绍了Next.js:如何从 getStaticProps 中获取静态资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Netlify CMS. I want to import all the slides for a carousel into my component. I made a collection called slider and added a few slides. That created two markdown files (one for each slide) in public/content/slider/. I would like to import them all into an iteratable object so I can build the carousel.

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

Because I have a webpack loader set up for markdown files, I can import a single markdown file no problem, like this:

从 '../public/content/posts/[post name].md 导入帖子

但是当我尝试使用 require.context 时,require-context,或者import fs,都不行.所以我决定尝试从 getStaticProps 中要求这些库.但是getStaticProps中的__dirname/,是我电脑文件系统的根目录.

But when I try to use require.context, require-context, or import fs, it's no good. So I decide to try requiring those libs from within getStaticProps. But __dirname in getStaticProps is /, the root of my computer's filesystem.

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

All the getStaticProps examples use data fetching. I'm missing some info. How can I import all the markdown files in the /slides/ folder?

推荐答案

这是一个Next.js 中的已知问题__dirname 按原样错误地解析为 /.

This is a known issue in Next.js, __dirname incorrectly resolves to / as it stands.

解决方法是使用 process.cwd() 代替.

The workaround is to use process.cwd() instead.

这篇关于Next.js:如何从 getStaticProps 中获取静态资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆