'Using inline images with Gatsby plugin mdx

I am pulling in data from airtable that uses an external URL inside of its quite long markdown, something like this:

...
testing 
<img src="https://via.placeholder.com/150" width="300px" />
...

However, when this is built and rendered, the image is still pointed to the external link and is not downloaded locally. Is there a way to transform incoming MDX images, download them, and then change the respective source to behave much like Gatsby's image would? It'd be nice for them to also get the progressive loading enhancements etc. That Gatsby offers.

The solutions offered here Gatsby Static Image(gatsby-plugin-image) inside MDX are not suitable, and the last answer in that post does not seem to work but maybe hints at a possible solution.

I also tried to use MDX provider and renderer to bake own my custom MDX renderer. It works fine if I want users to use some special react components, but obviously, it fails when I try to use it to intercept an img tag and replace it with Gatsby's StaticImage. This is because the external URL comes in as a prop, and is disallowed by gatsby static analyzer.



Solution 1:[1]

Ah! So this was a little bit of an adventure. Initially gatsby-remark-images-anywhere hit the mark, this got me closer, it now seemed like images were being picked up, but as soon as I upgraded the Gatsby 4, the thing broke.

A helpful commenter pointed out another package that nailed it, gatsby-remark-images-remote. This wasn't without its hiccups but it was doing the job.

So to recap, I used the mentioned package to achieve what I wanted. To take markdown that was coming in from Airtable, have it be run through MDX, AND also inline any foreign images. My Gatsby config ended up like this

{
      resolve: `gatsby-plugin-mdx`,
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: 'gatsby-remark-images-remote',
            options: {
              maxWidth: 300,
              linkImagesToOriginal: false,
              disableBgImage: true,
              backgroundColor: 'none',
            },
          },
        ],
        plugins: [`gatsby-remark-images-remote`],
      },
    },

I had to turn off some of Gatsby magic progressive loading due to some rendering issues. The package still has some kinks to workout but it successfully transformed all my img tags src attributes to point to the Gatsby static folder. No more links being rug-pulled :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ParthianShotgun