1 min read

⚙️ How to use absolute image paths in JSON — GatsbyJs

If you want to use images in JSON using gatsby-transformer-json this is the right place to get some help.
⚙️ How to use absolute image paths in JSON — GatsbyJs

If you want to use images in JSON imported with gatsby-transformer-json this is the right place to get some help.

Why

With the new version of Gatsby and the deprecation of gatsby-image something has changed. The images don’t show up on the page.

I’ve found the solution in an answer on Github under an issue that was asking something similar.

How to use absolute image paths in other files, e.g. JSON? · Discussion #31382 · gatsbyjs/gatsby · GitHub

Again, thank you so much LekoArts 🎉❤️

I know, I know. The issue speaks about  "absolute image paths" but this is the only solution that it’s actually working for me.

How

  • Make sure you already have gatsby-transformer-json installed, configured, and working.
  • Open your gatsby-node.js file and add this snippet:
const path = require("path")

const getFileNode = (options) => (source, _, context, info) => {
  const { fieldName } = info
  const partialPath = source[fieldName]

  if (!partialPath) {
    return null
  }

  const filePath = path.join(__dirname, options.path, partialPath)

  const fileNode = context.nodeModel.runQuery({
    firstOnly: true,
    type: 'File',
    query: {
      filter: {
        absolutePath: {
          eq: filePath
        }
      }
    }
  })

  if (!fileNode) {
    return null
  }

  return fileNode
}

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes, createFieldExtension } = actions

  createFieldExtension({
    name: "fileByAbsolutePath",
    args: {
      path: {
        type: "String!",
        defaultValue: ""
      }
    },
    extend: (options) => ({
      resolve: getFileNode(options)
    })
  })

  createTypes(`
    type LocalContentCities implements Node {
      image: File @fileByAbsolutePath(path: "src/images")
    }
  `)
}
  • Replace LocalContentCities with your actual resource name.

Done.

For the usage in your page/component just follow the instructions here: gatsby-plugin-image .

For any question I’m on Twitter, send me a DM.

Bye 👋