DEV Community

Cesar Varela
Cesar Varela

Posted on • Originally published at cesarvarela.com

How to load images in your MDX blog

If you've followed my previous posts about adding a blog to an existing Gatsby site, you'll notice one thing: images don't load.

Thankfully this is pretty easy to fix, so let's do it:

Add a gatsby-source-filesystem entry for your images

First, we need to let know Gatsby about the existence of our pictures. I want the images to reside inside the src/blog/images folder and not in src/images (skip this step if you don't care about this).

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `blog-images`,
        path: `${__dirname}/src/blog/images`,
      },
    },
Enter fullscreen mode Exit fullscreen mode

Add the gatsby-remark-images package

yarn add gatsby-remark-images
Enter fullscreen mode Exit fullscreen mode

or

npm i gatsby-remark-images
Enter fullscreen mode Exit fullscreen mode

And add it to your Gatsby config:

...
    `gatsby-remark-images`,
...
Enter fullscreen mode Exit fullscreen mode

Configure gatsby-plugin-mdx

Next, we need to tell gatsby-plugin-mdx to use gatsby-remark-images, and this is done on your Gatsby config too:

{
      resolve: `gatsby-plugin-mdx`,
      options: {
        root: __dirname,
        gatsbyRemarkPlugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 500,
              linkImagesToOriginal: false,
            },
          },
        ],
      },
    },
Enter fullscreen mode Exit fullscreen mode

Use them in your .mdx files

Once everything is ready, you should be able to include them like you would with .md files, using a relative path from the current .mdx you are writing on to the image:

...

![smart screen of death](./images/smart-screen.png)

...
Enter fullscreen mode Exit fullscreen mode

You can check an example here

Top comments (0)