Markdown Tutorials - Adding Images To Gatsby

2021-05-29

Add An Image

Adding image in a markdown file is pretty easy, just add this line of code:

![image_alt_description](./image_filename.jpg)

Note: The image file should be in the same directory or folder where the markdown file is located.

Then save, and ta-da!

Missing Image

Wait! What the f--- just happened!? Where is the image?

That's exactly my thought after saving my work. So, I did what my previous boss tells me when I freak out at times like this, "GMT, Leo, GMT..." GMT is short for "Google Mo, Tanga..." (Google it, stupid...) LOL!

Good thing Gatsby has good documentation (yeah I know, I used "good" twice), and found out about gatsby-remark-images. After spending an ample amount of time reading about it, there are a couple of things that needs to be done first for the images to render properly:

  • Install gatsby-remark-images
  • Configure gatsby-remark-images in gatsby-config.js

Install

npm install gatsby-remark-images

Note: gatsby-transformer-remark and gatsby-plugin-sharp are needed as well, I already have those installed in this site (yes, this site is built with Love and Gatsby)

Configure

Add the following in gatsby-config.js

// In your gatsby-config.js

plugins: [
  `gatsby-plugin-sharp`,
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        {
          resolve: `gatsby-remark-images`,
          options: {
            // It's important to specify the maxWidth (in pixels) of
            // the content container as this plugin uses this as the
            // base for generating different widths of each image.
            maxWidth: 590,
          },
        },
      ],
    },
  },
];

This is how I set it in my gatsby-config.js

        // ...

      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
            },
          },
          {
            resolve: `gatsby-remark-prismjs`,
            options: {

              // ...

Note: Config may vary depending on how you setup your site. So it needs a little code tinkering.

The moment of truth!

After installing necessary plugins and configuring gatsby-config.js, I added the markdown code for image, again, (lol!) :

![Rock Arc](./image01.jpg)

And it became (KoKo Krunch)!

Rock Arc

Nope not KoKo Krunch, but the image rendered properly this time. And I'm so happy that I feel like I can hack NASA using this image! (You know the feeling, no need to explain further...)

Let's add another one.

![Some Bridge](/images/image02.jpg)

Some Bridge

Works like a charm!

Final Thoughts

So, if you're using markdown as your data-source for your website built with Gatsby and stumble upon this little bump, enforce GMT, lol!

I'm done here.