Gatsby: [v2] Get source file's path from the node created by the gatsby-transformer-json plugin

Created on 13 Jul 2018  路  2Comments  路  Source: gatsbyjs/gatsby

Hi, migrating to v2 occurred an issue for me.

Into the onCreateNode method, when it was called after a node that has been created by the gatsby-transformer-json plugin, I used the node's id to extract the name of the source file. Now that the node's id is an UUID formatted value, nothing else in the node object is usable to make my code still working.

Is there any chance for you add a field containing the source file's path into the node object created by the gatsby-transformer-json plugin?

question or discussion

Most helpful comment

In your onCreateNode You can do something like this:

exports.onCreateNode = ({ node, getNode }) => {
  // need some filtering first so we only deal with json nodes - I'll skip this in example

  // json nodes created from files are children of File nodes, 
  // so we can get parent node and examine its properties
  const parentNode = getNode(node.parent)
  if (parentNode && parentNode.internal.type === `File`) {
    // `relativePath` is from memory - I don't remember what fields are really available there
    const fileName = parentNode.relativePath 
    // do something with fileName
  }
}

All 2 comments

In your onCreateNode You can do something like this:

exports.onCreateNode = ({ node, getNode }) => {
  // need some filtering first so we only deal with json nodes - I'll skip this in example

  // json nodes created from files are children of File nodes, 
  // so we can get parent node and examine its properties
  const parentNode = getNode(node.parent)
  if (parentNode && parentNode.internal.type === `File`) {
    // `relativePath` is from memory - I don't remember what fields are really available there
    const fileName = parentNode.relativePath 
    // do something with fileName
  }
}

Nice, thanks!

Was this page helpful?
0 / 5 - 0 ratings