~ / Home / Blog / How To Use Absolute Image Paths In Json — Gatsbyjs

12 Maggio 2021 • # javascript

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

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”)
    }
  `)
}

Done.

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

Vuoi lavorare con me?
Facciamo due chiacchiere.

hi@lucafedrizzi.com

░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░