1

I am making a blog using GatsbyJS + MDX. For the articles list page, I want to show the first several sentences/paragraphs of each article (just as you almost always see in a normal blog). However, I cannot figure out a way to do so in mdx.

For example, I cannot simply truncate the .mdx file (say truncate first 1000 bytes), otherwise we may end up having unclosed tags and so on, making mdx confused.

vldmrrdjcc
  • 2,082
  • 5
  • 22
  • 41
ch271828n
  • 15,854
  • 5
  • 53
  • 88

2 Answers2

1

gatsby-transformer-remark exposes an excerpt field that can be truncated to any desired length using pruneLength, which is a piece of the markdown body.

For example:

{
  allMarkdownRemark {
    edges {
      node {
        excerpt(pruneLength: 280)
      }
    }
  }
}

With the MDX, the outer node will differ from the snippet above but as long as you use gatsby-transformer-remark the excerpt will be available. You can use gatsby-transformer-remark by filling gatsbyRemarkPlugins object

{
  resolve: `gatsby-plugin-mdx`,
  options: {
    gatsbyRemarkPlugins: [
      {
        resolve: `gatsby-transformer-remark`,
      },
    ],
  },

For extremely customizable scenarios, you can use gatsby-plugin-excerpts plugin.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
1

If you use gatsby-plugin-mdx you can expose a part of your mdx file by add excerpt field into your query and specify the length of that part, Example:


query MyQuery {
  allMdx {
    nodes {
      excerpt(pruneLength: 100)
    }
  }
}

khalid
  • 71
  • 1
  • 3