在Gatsby构建过程中检索文件内容 [英] Retrieve file contents during Gatsby build
问题描述
我需要提取程序源文件的内容,以显示在Gatsby生成的页面中.我已经把所有东西都整理好了,应该可以打电话给我
I need to pull in the contents of a program source file for display in a page generated by Gatsby. I've got everything wired up to the point where I should be able to call
// my-fancy-template.tsx
import { readFileSync } from "fs";
// ...
const fileContents = readFileSync("./my/relative/file/path.cs");
但是,在运行gatsby develop
或gatsby build
时,出现以下错误
However, on running either gatsby develop
or gatsby build
, I'm getting the following error
未找到此依赖项: ⠀ * ./src/templates/my-fancy-template.tsx中的fs ⠀ 要安装它,您可以运行:npm install --save fs
This dependency was not found: ⠀ * fs in ./src/templates/my-fancy-template.tsx ⠀ To install it, you can run: npm install --save fs
但是,所有文档都建议该模块是Node 除非正在浏览器上运行.我还不太熟悉Node,但是考虑到gatsby build
也会失败(该命令甚至无法启动本地服务器),如果这是问题,我会有些惊讶.
However, all the documentation would suggest that this module is native to Node unless it is being run on the browser. I'm not overly familiar with Node yet, but given that gatsby build
also fails (this command does not even start a local server), I'd be a little surprised if this was the problem.
我什至从新的测试站点(gatsby new test
)尝试了同样的效果.
I even tried this from a new test site (gatsby new test
) to the same effect.
推荐答案
我在侧边栏中找到了此,并给出了镜头,但似乎声明了fs
可用;它实际上没有提供fs
.
I found this in the sidebar and gave that a shot, but it appears it just declared that fs
was available; it didn't actually provide fs
.
然后让我感到惊讶的是,尽管盖茨比在构建时创建了页面,但直到需要它们时,它才可能渲染.这可能是一个错误的评估,但最终导致了我需要的解决方案:
It then struck me that while Gatsby creates the pages at build-time, it may not render those pages until they're needed. This may be a faulty assessment, but it ultimately led to the solution I needed:
-
您需要在
gatsby-node.js
中的exports.onCreateNode
期间将文件内容添加到File
上的字段(假设您正在使用gatsby-source-filesystem
).您可以通过通常的方式进行此操作:
You'll need to add the file contents to a field on
File
(assuming you're usinggatsby-source-filesystem
) duringexports.onCreateNode
ingatsby-node.js
. You can do this via the usual means:
if (node.internal.type === `File`) {
fs.readFile(node.absolutePath, undefined, (_err, buf) => {
createNodeField({ node, name: `contents`, value: buf.toString()});
});
}
然后您可以在查询中的my-fancy-template.tsx
内访问此字段:
You can then access this field in your query inside my-fancy-template.tsx
:
{
allFile {
nodes {
fields { content }
}
}
}
从那里,您可以在allFile.nodes
的每个元素内自由使用fields.content
. (这当然也适用于file
查询方法.)
From there, you're free to use fields.content
inside each element of allFile.nodes
. (This of course also applies to file
query methods.)
自然,如果有人有一个更优雅的解决方案,我会欣喜若狂:-)
Naturally, I'd be ecstatic if someone has a more elegant solution :-)
这篇关于在Gatsby构建过程中检索文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!