Retrieve file contents during Gatsby build

假如想象 提交于 2019-12-06 14:37:22

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:

  1. You'll need to add the file contents to a field on File (assuming you're using gatsby-source-filesystem) during exports.onCreateNode in gatsby-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()});
        });
    }
    
  2. You can then access this field in your query inside my-fancy-template.tsx:

    { 
      allFile {
        nodes {
          fields { content }
        }
      }
    }
    

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 :-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!