Search code examples
markdowngatsbygatsby-remark-image

How to use gatsby-remark-images when the images aren't in the same folder of the markdown file


I am currently trying to create a blog using gatsby, where the blog posts are markdown files. The gatsby-transformer-remark and gatsby-remark-images works perfectly fine when your folder structure looks like this:

+-- content
|  +-- blog
|  |   +-- article_title
|  |   |   +-- article_title.md
|  |   |   +-- photo.png

So attachments must be in the same directory of the markdown files. Instead I would like to move all the attachments in a folder to make it easier to work with note taking apps like Obsidian.

+-- content
|  +-- blog
|  |   +-- media
|  |   |   +-- photo_1.png
|  |   |   +-- photo_2.png
|  |   |   +-- photo_3.png
|  |   +-- article_1.md
|  |   +-- article_2.md

Inside the article the images can be linked like this:

![This will be inserted in the alt attribute](photo1.png)
![This will be inserted in the alt attribute](./media/photo1.png)

I can't find a way to do it. My gatsby config file looks like this:

module.exports = {
  siteMetadata: {
    title: ``,
    description: ``,
    siteUrl: ``,
  },
  plugins: [
    "gatsby-plugin-postcss",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "media",
        path: `${__dirname}/content/blog/media`,
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "posts",
        path: `${__dirname}/content`,
        ignore: [`**/\.*`], // ignore files starting with a dot
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/assets`,
        name: `assets`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-remark-mathjax`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 590,
            },
          },
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 1.0725rem`,
            },
          },
          `gatsby-remark-prismjs`,
          `gatsby-remark-smartypants`,
        ],
      },
    },
    `gatsby-plugin-offline`,
    `gatsby-plugin-react-helmet`,
  ],
}


Solution

  • Your gatsby-config.js file looks good. However, I think you need to use relative paths directly, since the assets will transpiled directly to the public folder once compiled.

    Try using:

    ![This will be inserted in the alt attribute](/media/photo1.png)
    

    The point is that the path should be the public one where the image is available, so you may need to use blog/media/photo1.png path or similar.