我需要提取程序源文件的内容,以便在 Gatsby 生成的页面中显示。我已经把所有东西都连接到了我应该可以打电话的地方
// my-fancy-template.tsx
import { readFileSync } from "fs";
// ...
const fileContents = readFileSync("./my/relative/file/path.cs");
Run Code Online (Sandbox Code Playgroud)
但是,在运行gatsby develop或 时gatsby build,出现以下错误
未找到此依赖项: ? * fs 在 ./src/templates/my-fancy-template.tsx 中?要安装它,您可以运行: npm install --save fs
但是,所有文档都表明该模块是 Node 原生的,除非它在浏览器上运行。我还不太熟悉 Node,但考虑到它gatsby build也失败了(这个命令甚至没有启动本地服务器),如果这是问题所在,我会有点惊讶。
我什至从一个新的测试站点 ( gatsby new test) 尝试了同样的效果。
我发现这个在侧边栏,并给了一个球,但似乎只是宣布那fs是可利用的; 它实际上并没有提供fs.
然后让我震惊的是,虽然 Gatsby 在构建时创建页面,但它可能不会在需要这些页面之前呈现这些页面。这可能是一个错误的评估,但它最终导致了我需要的解决方案:
您需要在in期间将文件内容添加到 on File(假设您正在使用gatsby-source-filesystem)的字段exports.onCreateNode中gatsby-node.js。您可以通过通常的方式做到这一点:
if (node.internal.type === `File`) {
fs.readFile(node.absolutePath, undefined, (_err, buf) => {
createNodeField({ node, name: `contents`, value: buf.toString()});
});
}
Run Code Online (Sandbox Code Playgroud)然后,您可以在查询中访问此字段my-fancy-template.tsx:
{
allFile {
nodes {
fields { content }
}
}
}
Run Code Online (Sandbox Code Playgroud)从那里,您可以fields.content在allFile.nodes. (这当然也适用于file查询方法。)
当然,如果有人有更优雅的解决方案,我会欣喜若狂:-)
| 归档时间: |
|
| 查看次数: |
877 次 |
| 最近记录: |