Search code examples
gatsby

How do I link to internal images in my markdown post in gatsbyjs?


Goal: I'm trying to link to an image I have located in my images folder from a markdown post:

This is supposed to be a [link](../images/image.png) to my image.

When clicking the link, I'm expecting it to lead to a page containing the image only.

Problem: I'm trying to use a relative path as this is also how I would give the path if I was actually displaying the image (![alt text](../images/image.png)).

However, gatsbyjs does not seem to recognise the relative path as image source and tries to go to the page domain/images/image.png, which is not the url gatsbyjs reserves for the image (it will be a randomly generated one).

Question: Is there an easy way of linking to my image?


Solution

  • Complete Re-edit of answer:

    /static
     /images
      imagefile
    

    the above will create an images folder in your /public directory.

    You can then source this in your markdown each time as [link](/images/imageFile.extension). This is a little bit of a 'hands on' approach and would require manually loading in your images to static.

    The Gatsby way:

    Place this inside your gatsby-node

    import path from 'path';
    import fsExtra from 'fs-extra';
    
    export const onCreateNode = async ({
      node, actions
    }) => {
      const sourceNorm = path.normalize(`${__dirname}/src/images`);
      const destination = `/images`;
    
      if (node.internal.type === 'File') {
        const dir = path.normalize(node.dir);
    
        if (dir.includes(sourceNorm)) {
          const relativeToDestination = dir.replace(sourceNorm, '');
          const newPath = path.join(
            process.cwd(),
            'public',
            destination,
            relativeToDestination,
            node.base
          );
    
          fsExtra.copy(node.absolutePath, newPath, err => {
            if (err) {
              console.log('Error copying file: ', err)
            }
          })
        }
      }
    }
    
    

    The above will take all of your images that are specified in /src/images and create nodes for them in the public folder during build/develop to the destination at /images/.

    You should then be able to link to your images with /images/image.extension 🚀