gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.21k stars 10.33k forks source link

Unable to view images from the body of a Markdown file in GatsbyJS #16612

Closed jnsrikanth closed 5 years ago

jnsrikanth commented 5 years ago

Description

I am trying to display images from a Markdown file especially from the body of the markdown file but unable to see them.

I am using the recommended plugin configuration by the official GatsbyJS documentation for embedding images in Markdown files. However, I am unable to achieve the same. I can view the images from the frontmatter using GraphQL queries but unable to view the body inline images in the markdown file.

Steps to reproduce

I have the below gatsby-config.js

const guid = process.env.NETLIFY_GOOGLE_ANALYTICS_ID;

module.exports = {
  siteMetadata: {
    title: 'Apple Software',
    description: 'my theme',
    contact: {
      phone: '+91 999999999',
      email: 'info@abcxyz.com',
    },
    menuLinks: [
      {
        name: 'Services',
        link: '/services',
      },
      {
        name: 'Team',
        link: '/team',
      },
      {
        name: 'Testimonials',
        link: '/testimonials',
      },
      {
        name: 'Blog',
        link: '/blog',
      },
      {
        name: 'Contact',
        link: '/contact',
      },
      {
        name: 'Work',
        link: '/work',
      },
      {
        name: 'Courses',
        link: '/carousel',
      },
      {
        name: 'Careers',
        link: '/careers',
      },
    ],
  },
  plugins: [
    'gatsby-plugin-sass',
    'gatsby-transformer-json',
    'gatsby-transformer-remark',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/data`,
        name: 'data',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/images`,
        name: 'images',
      },
    },
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: guid ? guid : 'UA-XXX-1',
        // Puts tracking script in the head instead of the body
        head: false,
      },
    },
  `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,
          },
        },
      ],
    },
  },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 1200,
            },
          },
        ],
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages`,
      },
    },
  ],
};

I am using the below Markdown file for displaying content and images. As you can see the image from the frontmatter, I am able to display but I am unable to display the body inline-image 'Default Image' inside this markdown file.

---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: 'services/default.png'
---

Lorem markdownum aequalis strigis. _Saetigeri iubeas_, vultu huic alvum nondum
de obside ut laniavit arbor palmis, cum quin. Rupes vetat videndo, armigerae
crimen habet Priamum nec.

## Ne verba patulosque numen vix libet

![Default Image](./default.png)

Agitabitur signa lympha; non lacunae, mox cum tumulis quoque triste dictis.
Ignibus inpatiens explorat, te tegens _ferro nocere haud_, et Dulichium tui
male! Quo sed [fuit flexit et](#vexant-achivi) hic die solido, gloria?

1. Cum det dixit Parcarum qui spemque est
2. Exit ex huic
3. Quod consiste agitataque claustraque vicina videt lacertis
4. Loquor videt
5. Ardua non igne caelesti coniugis cognovi diversorum
6. Per nunc pariterque saeva vindicet

Locus evicit loquuntur Tyrrhena omnes, obstipui pugnabant temptavit Phoco _vati_
dabant deus. Memorata haberet sepulcrales gentisque dum sic, in flumina templa!
Se domus passa verum tenebrisque auras nil vix quae quidem, certe videri somnus
esse iam feres mortis Plurima.

## Postquam tamen

Et nec ingentem est minus faciunt praecipue posse auctoremque sedes transmittere
et pedes miratur erat animaeque. Tellus admonuit humanam funes, sagittis et
licet! Inserui quamvis Clymeni.

- Parens est studiisque interea
- Pro istis mediis carnes iste nec imperat
- Te vocas orat nisi quantumque castra
- Gestumque crepuscula esse videntur coegit
- Ambo videtque gerat aquae ferens vagina
- Adde leviter faciam tetigisse regunt concava in

Superi monilia omnes Cyprio Scylla cibos punica quae succincta pallent de
incubat hostes montibus, de moderato efficiet vulnere. Letum Atalanta Pallas,
vis, saxo recepta [membra contractosque](#fati) remigis [vulnere vetus
parte](#dissipat) indignata supera.

Expected result

What should happen?

Actual result

What happened.

Environment

I am using GatsbyJS V2 and all the Gatsby Plugins are V2 and above.

System: OS: Windows 7 CPU: (4) x64 Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz Binaries: npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD npmPackages: gatsby: ^2.0.33 => 2.13.51 gatsby-plugin-google-analytics: ^2.0.14 => 2.1.6 gatsby-plugin-mdx: ^1.0.24 => 1.0.24 gatsby-plugin-react-helmet: ^3.0.4 => 3.1.3 gatsby-plugin-sass: ^2.0.7 => 2.1.4 gatsby-plugin-sharp: ^2.2.11 => 2.2.11 gatsby-remark-images: ^3.1.11 => 3.1.11 gatsby-source-filesystem: ^2.0.12 => 2.1.8 gatsby-transformer-json: ^2.1.6 => 2.2.2 gatsby-transformer-remark: ^2.1.15 => 2.6.10

Run gatsby info --clipboard in your project directory and paste the output here.

jonniebigodes commented 5 years ago

@jnsrikanth i've picked up on your issue and based on your information below are the steps i took to triage your issue.

no_markdown_1_files

The accounting markdown is almost identical to yours, only a couple things diferent and those are, the frontmatter is now

---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: ./default.jpg
---

And this small change will allow gatsby-transformer-sharp and gatsby-plugin-sharp and gatsby-image apply lazy loading and all the other features available.

And changed the image reference in the markdown content, that is now:

![Default Image](./default.jpg)

export const query= graphql query myMarkdown($title: String!) { markdownRemark(frontmatter: {title: {eq: $title}}) { frontmatter { title image { childImageSharp { fluid(maxWidth: 600){ ...GatsbyImageSharpFluid } } } } html } } export default DummyTemplate


Issued `gatsby develop` and waited for the process to complete, it went through without any issues and opening up a new browser window to `http://localhost:8000/services/accounting` i'm presented with the following:
![no_markdown_2_cover](https://user-images.githubusercontent.com/22988955/63060237-93edbf80-bee9-11e9-86ba-c4db5de70e85.png)

and the markdown with a image inside being rendered.
![no_markdown_3_markdown_embedded](https://user-images.githubusercontent.com/22988955/63060257-a49e3580-bee9-11e9-9fa2-b71db3c3d543.png)

One extra thing, i saw a reference to `theme` somewhere  in the description, if this is the case then this reproduction will probably will need some tweaks. Otherwise based on your description and what i mentioned in my response will allow you to render the image inside the markdown.

Also if you want i can hoist the code to a github repo so that you can look at it at your own pace and compare it to your own code.

Feel free to provide feedback so that we can close this issue or continue to work on it until we find a suitable solution.
jnsrikanth commented 5 years ago

Hi @jonniebigodes,

Thanks for researching and recreating my setup with your suggested fixes/modifications. I have been successfully been able to view images inside the body of my markdown files. However, I do have a few queries/observations.

  1. I see that you have disabled the mdx plugin in the gatsby config file. Can you elaborate why? In my case, I have retained that plugin and still was able to see the result (i.e. get the images to be viewed from the markdown body). Can you point out to the real value-add of mdx in markdown from a Gatsby point of view?
  2. You have noted in your response that you made some minor modifications in the YAML frontmatter, but I see that both the frontmatter (the one posted by me and the one suggested by you) seem identical. What is the difference? Could you please elaborate on that.

Thank You. @jnsrikanth

jnsrikanth commented 5 years ago

@jonniebigodes Could you also please submit the repo and share the link? Thank You.

jonniebigodes commented 5 years ago

@jnsrikanth regarding your questions

1- I disabled the mdx plugin simply because the focus of the issue was markdown images being rendered and to keep the reproduction simple i left it out. If based on your feedback should the need to include and configure the said plugin, then i would update my reproduction accordingly.

One of the core features of the said plugin is the ability to incorporate jsx directly into the markdown and the plugin and it's dependencies will parse it and display it seamlessly in your gatsby site. This can be a really good thing if you want more flexibility when you write your content.

Now depending on your use case and what you want to achieve if the markdown content is similar to the one you're listed in your issue description i would leave it to gatsby-transformer-remark to process it and display it for time being. And invest a bit of time reading and fiddling with the possibilities of what you can do with the gatsby-plugin-mdx and in a future iteration of your site go with that approach for a richer experience.

2- Regarding this question the file is almost identical, but asides from the file extension for the img, if you look carefully you see that yours has the following structure

---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: 'services/default.png'
---

When you issue a graphql query that will fetch that field and you want to use gatsby-image and both gatsby sharp plugins. Something like the following:

 query myMarkdown($title: String!) {
        markdownRemark(frontmatter: {title: {eq: $title}}) {
            frontmatter {
                title
                image {
                    childImageSharp {
                        fluid(maxWidth: 600){
                            ...GatsbyImageSharpFluid
                        }
                    }
                }
            }
            html
        }
    }

you might encounter a issue saying that Field "image" must not have a selection since type "String" has no subfields., this happens because during the build process when gatsby generates the nodes it will read that one like a string node instead of a file node.

And to avoid extra steps, as the image is a "sibling" of the markdown file, meaning is inside of the same folder i modified to the following:

---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: ./default.jpg
---

With this small tweak, when gatsby is going through the build process it will interpret the image key as a file node and allow you to use the graphql query above and both sharp plugins without issues.

The code used for the reproduction is hosted here and a live version here

jnsrikanth commented 5 years ago

closing this as the issue has been resolved as per the solution from @jonniebigodes

karansapolia commented 2 years ago

Thank you @jonniebigodes for the solution! I was really struggling trying to find out ways to resolve this issue. I realize I desperately need to upgrade my website from Gatsby 2. Thanks again.