Skip to content

Commit

Permalink
Improve docs for setting up a Gatsby application that pulls content f…
Browse files Browse the repository at this point in the history
…rom Markdown files (gatsbyjs#13851)

* adds example with markdown pages

* Improves Adding Markdown Pages tutorial

* wording

* lints
updates example and markdown file according to eslint rules
lints README
lints post-1

* addresses review

* Update docs/docs/adding-markdown-pages.md

Co-Authored-By: Marcy Sutton <[email protected]>

* update to match Style Guide
  • Loading branch information
paschalidi authored and Marcy Sutton committed Jun 6, 2019
1 parent 19466a2 commit 31ee1d0
Show file tree
Hide file tree
Showing 17 changed files with 975 additions and 33 deletions.
85 changes: 52 additions & 33 deletions docs/docs/adding-markdown-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,80 +2,93 @@
title: Adding Markdown Pages
---

Gatsby can use markdown files to create pages in your site.
You add plugins to read and understand folders with markdown files and from them create pages automatically.
Gatsby can use Markdown files to create pages in your site.
You add plugins to read and understand folders with Markdown files and from them create pages automatically.

Here are the steps Gatsby follows for making this happen.

1. Read files into Gatsby from the filesystem
2. Transform markdown to HTML and frontmatter to data
3. Create a page component for the markdown files
4. Programmatically create pages using Gatsby's Node.js `createPage` API
2. Transform Markdown to HTML and [frontmatter](#including-frontmatter) to data
3. Add a Markdown file
4. Create a page component for the Markdown files
5. Create static pages using Gatsby's Node.js `createPage` API

### Read files into Gatsby from the filesystem - `gatsby-source-filesystem`
## Read files into Gatsby from the filesystem

Use the plugin [`gatsby-source-filesystem`](/packages/gatsby-source-filesystem/#gatsby-source-filesystem) to read files.

#### Install

`npm install --save gatsby-source-filesystem`

Now open `gatsby-config.js` to add this plugin to the plugin array.
#### Add plugin

To add a plugin, add either a string (the plugin name) or to pass options, an object.
For `gatsby-source-filesystem` we pass an object so we can set the file system path:
**NOTE:** There are two ways to add a plugin in `gatsby-config.js`. Either you can pass a string with the plugin name or in case you want to include options, pass an object.

Open `gatsby-config.js` to add the `gatsby-source-filesystem` plugin. Now pass the object from the next block to the `plugins` array. By passing an object that includes the key `path`, you set the file system path.

```javascript:title=gatsby-config.js
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/path/to/markdown/files`,
name: "markdown-pages",
name: `markdown-pages`,
path: `${__dirname}/src/markdown-pages`,
},
},
]
```

Now that we've "sourced" the markdown files from the filesystem, we can now "transform" the markdown to HTML and the YAML frontmatter to JSON.
Completing the above step means that you've "sourced" the Markdown files from the filesystem. You can now "transform" the Markdown to HTML and the YAML frontmatter to JSON.

### Transform Markdown to HTML and frontmatter to data using `gatsby-transformer-remark`

### Transforming markdown — `gatsby-transformer-remark`
You'll use the plugin [`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/) to recognize files which are Markdown and read their content. The plugin will convert the frontmatter metadata part of your Markdown files as `frontmatter` and the content part as HTML.

We'll use the plugin [`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/) to recognise files which are markdown and read its content. It will convert the frontmatter metadata part of your markdown file as `frontmatter` and the content part as HTML.
#### Install

`npm install --save gatsby-transformer-remark`

#### Add plugin

Add this to `gatsby-config.js` after the previously added `gatsby-source-filesystem`.

```javascript:title=gatsby-config.js
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/path/to/markdown/files`,
name: "markdown-pages",
path: `${__dirname}/src/markdown-pages`,
name: `markdown-pages`,
},
},
`gatsby-transformer-remark`,
]
```

#### Note on creating markdown files.
### Add a Markdown file

When you create a Markdown file, at the top of the file, add the block below. You can have different key value pairs that are relevant to your website. This block will be parsed by `gatsby-transformer-remark` as `frontmatter`. The GraphQL API will provide this data in our React components.
Create a folder in the `/src` directory of your Gatsby application called `markdown-pages`.
Now create a Markdown file inside it with the name `post-1.md`.

```
#### Including frontmatter

When you create a Markdown file, at the top of the file, add the frontmatter (metadata) block below. You can have different key value pairs that are relevant to your website. This block will be parsed by `gatsby-transformer-remark` as `frontmatter`. The GraphQL API will provide this data in your React components.

```markdown:title=src/markdown-pages/post-1.md
---
path: "/blog/my-first-post"
date: "2017-11-07"
date: "2019-05-04"
title: "My first blog post"
---
```

### Create a page template for the markdown data.
What is important in this step is the key pair `path`. The value that is assgined to the key `path` is used in order to navigate to your post.

### Create a page template for the Markdown files

Create a folder in the `/src` directory of your Gatsby application called `templates`.
Now create a `blogTemplate.js` inside it with the following content.
Now create a `blogTemplate.js` inside it with the following content:

```jsx:title=src/templates/blogTemplate.js
import React from "react"
Expand Down Expand Up @@ -114,20 +127,24 @@ export const pageQuery = graphql`
`
```

Two things are important in the file above.
Two things are important in the file above:

1. A GraphQL query is made in the second half of the file to get the Markdown data. Gatsby has automagically given you all the Markdown metadata and HTML in this query's result.

**Note: To learn more about GraphQL, consider this [excellent resource](https://www.howtographql.com/)**
2. The result of the query is injected by Gatsby into the `Template` component as `data`. `markdownRemark` is the property that we find has all the details of the Markdown file. We can use that to construct a template for our blogpost view. Since it's a React component, you could style it with any of the recommended styling systems in Gatsby.

### Create static pages using Gatsby's Node API.
2. The result of the query is injected by Gatsby into the `Template` component as `data`. `markdownRemark` is the property that you'll find has all the details of the Markdown file. You can use that to construct a template for our blog post view. Since it's a React component, you could style it with any of the [recommended styling systems](/docs/styling/) in Gatsby.

Gatsby exposes a powerful Node.js API, which allows for functionality such as creating dynamic pages. This API is available in the `gatsby-node.js` file in the root directory of your project, at the same level as `gatsby-config.js`. Each export found in this file will be run by Gatsby, as detailed in its [Node API specification](/docs/node-apis/). However, we only care about one particular API in this instance, `createPages`.
### Create static pages using Gatsby’s Node.js `createPage` API

Gatsby calls the `createPages` API (if present) at build time with injected parameters, `actions` and `graphql`. Use the `graphql` to query Markdown file data as below. Next use `createPage` action creator to create a page for each of the Markdown files using the `blogTemplate.js` we created in the previous step.
Gatsby exposes a powerful Node.js API, which allows for functionality such as creating dynamic pages. This API is available in the `gatsby-node.js` file in the root directory of your project, at the same level as `gatsby-config.js`. Each export found in this file will be run by Gatsby, as detailed in its [Node API specification](/docs/node-apis/). However, you should only care about one particular API in this instance, `createPages`.

Use the `graphql` to query Markdown file data as below. Next, use the `createPage` action creator to create a page for each of the Markdown files using the `blogTemplate.js` you created in the previous step.

**NOTE:** Gatsby calls the `createPages` API (if present) at build time with injected parameters, `actions` and `graphql`.

```javascript:title=gatsby-node.js
const path = require("path")
const path = require(`path`)

exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions
Expand All @@ -154,7 +171,7 @@ exports.createPages = ({ actions, graphql }) => {
return Promise.reject(result.errors)
}

result.data.allMarkdownRemark.edges.forEach(({ node }) => {
return result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: blogPostTemplate,
Expand All @@ -165,12 +182,14 @@ exports.createPages = ({ actions, graphql }) => {
}
```

This should get you started on some basic markdown power in your Gatsby site. You can further customise the `frontmatter` and the template file to get desired effects!
This should get you started on some basic Markdown functionality in your Gatsby site. You can further customize the frontmatter and the template file to get desired effects!

For more information, have a look in the working example `using-markdown-pages`. You can find it in the [Gatsby examples section](https://github.com/gatsbyjs/gatsby/tree/master/examples).

## Other tutorials

Check out tutorials listed on the [Awesome Gatsby](/docs/awesome-gatsby/#gatsby-tutorials) page for more looks at building Gatsby sites with markdown.
Check out tutorials listed on the [Awesome Gatsby](/docs/awesome-gatsby/#gatsby-tutorials) page for more information on building Gatsby sites with Markdown.

## Gatsby markdown starters
## Gatsby Markdown starters

There are a number of [Gatsby starters](/starters?c=Markdown) that come preconfigured to work with markdown.
There are also a number of [Gatsby starters](/starters?c=Markdown) that come pre-configured to work with Markdown.
1 change: 1 addition & 0 deletions examples/using-markdown-pages/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
14 changes: 14 additions & 0 deletions examples/using-markdown-pages/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Using Markdown Pages

Demonstrates how to render Markdown files as pages in you Gatsby application.

## Running an example site

1. Clone `gatsby` repository `git clone [email protected]:gatsbyjs/gatsby.git`
2. Navigate to the example `cd gatsby/examples/using-markdown-pages`
3. Install the dependencies for the application by running `yarn`
4. Run the Gatsby development server `gatsby develop`

## References

- [Adding Markdown Pages](https://www.gatsbyjs.org/docs/adding-markdown-pages/)
7 changes: 7 additions & 0 deletions examples/using-markdown-pages/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Implement Gatsby's Browser APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/browser-apis/
*/

// You can delete this file if you're not using it
39 changes: 39 additions & 0 deletions examples/using-markdown-pages/gatsby-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module.exports = {
siteMetadata: {
title: `gatsby-example-using-markdown-pages`,
description: `Start your new blog using markdown files`,
author: `@gatsbyjs`,
},
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown-pages`,
path: `${__dirname}/src/markdown-pages`,
},
},
`gatsby-transformer-remark`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`,
},
},
],
}
36 changes: 36 additions & 0 deletions examples/using-markdown-pages/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const path = require(`path`)

exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions

const blogPostTemplate = path.resolve(`src/templates/blogTemplate.js`)

return graphql(`
{
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
limit: 1000
) {
edges {
node {
frontmatter {
path
}
}
}
}
}
`).then(result => {
if (result.errors) {
return Promise.reject(result.errors)
}

return result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: blogPostTemplate,
context: {}, // additional data can be passed via context
})
})
})
}
7 changes: 7 additions & 0 deletions examples/using-markdown-pages/gatsby-ssr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/ssr-apis/
*/

// You can delete this file if you're not using it
37 changes: 37 additions & 0 deletions examples/using-markdown-pages/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "gatsby-example-using-markdown-pages",
"private": true,
"description": "Start your new blog using markdown files",
"version": "0.1.0",
"author": "@gatsbyjs",
"dependencies": {
"gatsby": "^2.3.34",
"gatsby-image": "^2.0.41",
"gatsby-plugin-manifest": "^2.0.29",
"gatsby-plugin-offline": "^2.0.25",
"gatsby-plugin-react-helmet": "^3.0.12",
"gatsby-plugin-sharp": "^2.0.35",
"gatsby-source-filesystem": "^2.0.33",
"gatsby-transformer-remark": "^2.3.12",
"gatsby-transformer-sharp": "^2.1.18",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-helmet": "^5.2.1"
},
"devDependencies": {
"prettier": "^1.17.0"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write src/**/*.{js,jsx}",
"start": "npm run develop",
"serve": "gatsby serve",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
}
}
42 changes: 42 additions & 0 deletions examples/using-markdown-pages/src/components/header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Link } from "gatsby"
import PropTypes from "prop-types"
import React from "react"

const Header = ({ siteTitle }) => (
<header
style={{
background: `rebeccapurple`,
marginBottom: `1.45rem`,
}}
>
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `1.45rem 1.0875rem`,
}}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
style={{
color: `white`,
textDecoration: `none`,
}}
>
{siteTitle}
</Link>
</h1>
</div>
</header>
)

Header.propTypes = {
siteTitle: PropTypes.string,
}

Header.defaultProps = {
siteTitle: ``,
}

export default Header
Loading

0 comments on commit 31ee1d0

Please sign in to comment.