GatsbyJS - Adding the display of post's list in the app

gatsby-source-filesystem (plugin)

This plugin provides the access to app's file-system. It adds specific nodes in GraphQL scheme of the app

Installation

Install gatsby-source-filesystem in your GatsbyJS app

  1. npm install gatsby-source-filesystem
  2. set up plugin in gatsby-config.js
// gatsby-config.js
{
...
    plugins: [
        ...
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            path: `${__dirname}/src/posts`,
            name: "posts",
          },
        },
    ]
}

Create the post

Create markdown post in /src/posts, for example greetings.md

GraphQL query of the plugin

gatsby-source-filesystem - How to query (gatsbyjs.com)

Open the GraphQL Editor on http://localhost:8000/__graphql

Example

{
  allFile {
    edges {
      node {
        extension
        name
      }
    }
  }
}

Response

{
  "data": {
    "allFile": {
      "edges": [
        ...
        {
          "node": {
            "extension": "md",
            "name": "greetings"
          }
        }
      ]
    }
  },
  "extensions": {}
}

gatsby-transformer-remark (plugin)

This plugin is a markdown parser

Installation

npm:

npm install gatsby-transformer-remark

yarn:

yarn add gatsby-transformer-remark

In gatsby-config.js:

{
    plugins: [
        ...
        `gatsby-transformer-remark`,
    ]
}

After re-run the app you can use new node allMarkdownRemark in GraphQL editor that is provided by the plugin

GraphQL query of the plugin

Query

{
  allMarkdownRemark {
    totalCount
    edges {
      node {
        html
        excerpt
        frontmatter {
          title
          slug
          date(formatString: "DD-MM-YYYY")
        }
      }
    }
  }
}
  • totalCount is the count of markdown files in the app
  • edges
    • node is each node (file)
      • html is html layout of the file
      • except the first text of the post's content with limit
    • frontmatter

Response

{
  "data": {
    "allMarkdownRemark": {
      "totalCount": 1,
      "edges": [
        {
          "node": {
            "html": "<h1>Greetings!</h1>",
            "excerpt": "Greetings!",
            "title": "My First Post",
            "slug": "/greetings-post",
            "date": "16-12-2020"
          }
        }
      ]
    }
  },
  "extensions": {}
}
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List