73 |
74 | #### Frontmatter
75 |
76 | Frontmatter, i.e. in a [Gastby][gatsby] blog post, is preserved as authored.
77 |
78 |
79 | ---
80 | title: Hello World
81 | tags:
82 | - Some Tag
83 | - Another Tag
84 | ---
85 |
86 | ```javascript
87 | // this will be prettified
88 | var a = 'a';
89 |
90 | ```
91 |
92 |
93 | [prettier]: https://github.com/prettier/prettier
94 | [gatsby]: https://gatsbyjs.org
95 |
--------------------------------------------------------------------------------
/__fixtures__/css.md:
--------------------------------------------------------------------------------
1 | ```css
2 | p {
3 | color: red;
4 | }
5 |
6 | body {
7 | font-family: 'Georgia', sans-serif;
8 | }
9 |
10 | ```
11 |
--------------------------------------------------------------------------------
/__fixtures__/file-with-errors.md:
--------------------------------------------------------------------------------
1 | This file has errors goober
2 |
3 | ```typescript
4 | class Hello extends React.Component {
5 | render() {
6 | ...
7 | }
8 | }
9 |
10 | ```
--------------------------------------------------------------------------------
/__fixtures__/front-matter.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Hello World'
3 | tags: ["asdf", "asdf1"]
4 | ---
5 |
6 | Some content
7 |
8 | ```javascript
9 | var a = 'a';
10 |
11 | ```
12 |
--------------------------------------------------------------------------------
/__fixtures__/graphql.md:
--------------------------------------------------------------------------------
1 | ```graphql
2 | {
3 | empireHero: hero(episode: EMPIRE) {
4 | name
5 | }
6 | jediHero: hero( episode: JEDI) {
7 | name
8 | }
9 | }
10 | ```
11 |
--------------------------------------------------------------------------------
/__fixtures__/javascript-lines.md:
--------------------------------------------------------------------------------
1 | ```javascript
2 | var lines = 3;
3 |
4 |
5 |
6 | ```
7 |
--------------------------------------------------------------------------------
/__fixtures__/javascript-multiple-same.md:
--------------------------------------------------------------------------------
1 | ```javascript{1-2}
2 | const a = 'b';
3 | const b = 'c';
4 |
5 | alert('hello world');
6 | ```
7 |
8 | Content
9 |
10 | ```javascript{1-2}
11 | const a = 'b';
12 | const b = 'c';
13 |
14 | alert('hello world');
15 | ```
16 |
17 | Content
18 |
19 | ```javascript{1-2}
20 | const a = 'b';
21 | const b = 'c';
22 |
23 | alert('hello world');
24 | ```
25 |
--------------------------------------------------------------------------------
/__fixtures__/javascript-multiple.md:
--------------------------------------------------------------------------------
1 | ```javascript
2 | const path = require('path');
3 | const { prettierMarkdown } = require('@dschau/prettier-markdown');
4 |
5 | prettierMarkdown(
6 | ['README.md', 'blog/posts/2017-01-01-hello-world/index.md'].map(file =>
7 | path.join(process.cwd(), file)
8 | )
9 | ).then(files => {
10 | // array of files that were written
11 | });
12 |
13 | ```
14 |
15 | ```javascript{1-2}
16 | const a = 'b';
17 | const b = 'c';
18 |
19 | alert('hello world');
20 | ```
21 |
--------------------------------------------------------------------------------
/__fixtures__/javascript.md:
--------------------------------------------------------------------------------
1 | ```javascript
2 | var a = 'i am ugly'
3 | var b = "super ugly";
4 |
5 | alert('sup')
6 | ```
7 |
--------------------------------------------------------------------------------
/__fixtures__/json.md:
--------------------------------------------------------------------------------
1 | ```json
2 | {
3 | "asdf": "asdf",
4 |
5 | "value": true,
6 |
7 | "other_value": false
8 | }
9 | ```
10 |
--------------------------------------------------------------------------------
/__fixtures__/kitchen-sink.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Creating a Blog with Gatsby
3 | path: "/getting-started-with-gatsby"
4 | date: "2017-07-17T17:12:33.962Z"
5 | tags: ["gatsby", "react", "javascript"]
6 | image: "preview.png"
7 | excerpt: "Gatsby is an incredible static site generator that lets you build a static site that still has all the benefits expected from a modern web application…"
8 | ---
9 |
10 | *This blog post was originally published at [Object Partners, Inc.](https://objectpartners.com/2017/07/19/creating-a-static-blog-with-gatsby/), and has since been cross-posted at the [official gatsby blog](https://www.gatsbyjs.org/blog/2017-07-19-creating-a-blog-with-gatsby/)*
11 |
12 | Gatsby is an incredible static site generator that allows for React to be used as the underlying rendering engine to scaffold out a static site that truly has all the benefits expected in a modern web application. It does this by rendering dynamic React components into static HTML content via [server side rendering][react-dom-server] at build time. This means that your users get all the benefits of a static site such as the ability to work without JavaScript, search engine friendliness, speedy load times, etc. without losing the dynamism and interactivity that is expected of the modern web. Once rendered to static HTML, client-site React/JavaScript _can_ take over (if creating stateful components or logic in `componentDidMount`) and add dynamism to the statically generated content.
13 |
14 | Gatsby [recently released][gatsby-release] a v1.0.0 with a bunch of new features, including (but not limited to) the ability to create content queries with GraphQL, integration with various CMSs--including WordPress, Contentful, Drupal, etc., and route based code splitting to keep the end-user experience as snappy as possible. In this post, we'll take a deep dive into Gatsby and some of these new features by creating a static blog. Let's get on it!
15 |
16 | ## Getting started
17 |
18 | ### Installing the CLI
19 |
20 | `npm install -g gatsby`
21 |
22 | Gatsby ships with a great CLI (command line interface) that contains the functionality of scaffolding out a working site, as well as commands to help develop the site once created.
23 |
24 | `gatsby new personal-blog && cd $_`
25 |
26 | This command will create the folder `personal-blog` and then change into that directory. A working `gatsby` statically generated application can now be developed upon. The Gatsby CLI includes many common development features such as `gatsby build` (build a production, statically generated version of the project), `gatsby develop` (launch a hot-reload enabled web development server), etc.
27 |
28 | We can now begin the exciting task of *actually* developing on the site, and creating a functional, modern blog. You'll generally want to use `gatsby develop` to launch the local development server to validate functionality as we progress through the steps.
29 |
30 | ## Adding necessary plugins
31 |
32 | Gatsby supports a [rich plugin interface][gatsby-plugins], and many incredibly useful plugins have been authored to make accomplishing common tasks a breeze. Plugins can be broken up into three main categories: **functional** plugins, **source** plugins, and **transformer** plugins.
33 |
34 | ### Functional plugins
35 |
36 | Functional plugins either implement some functionality (e.g. offline support, generating a sitemap, etc.) _or_ they extend Gatsby's webpack configuration adding support for typescript, sass, etc.
37 |
38 | For this particular blog post, we want a single page app-like feel (without page reloads), as well as the ability to dynamically change the `title` tag within the `head` tags. As noted, the Gatsby plugin ecosystem is rich, vibrant, and growing, so oftentimes a plugin already exists that solves the particular problem you're trying to solve. To address the functionality we want for _this_ blog, we'll use the following plugins:
39 |
40 | - [`gatsby-plugin-catch-links`][gatsby-plugin-catch-links]
41 | - implements the history `pushState` API, and does not require a page reload on navigating to a different page in the blog
42 | - [`gatsby-plugin-react-helmet`][gatsby-plugin-react-helmet]
43 | - [react-helmet][react-helmet] is a tool that allows for modification of the `head` tags; Gatsby statically renders any of these `head` tag changes
44 |
45 | with the following command:
46 |
47 | ```bash
48 | yarn add gatsby-plugin-catch-links gatsby-plugin-react-helmet
49 | ```
50 |
51 | We're using [yarn][yarn], but npm can just as easily be used with `npm i --save [deps]`.
52 |
53 | After installing each of these functional plugins, we'll edit `gatsby-config.js`, which Gatsby loads at build-time to implement the exposed functionality of the specified plugins.
54 |
55 | ```javascript{6-9}
56 | module.exports = {
57 | siteMetadata: {
58 | title: `Your Name - Blog`,
59 | author: `Your Name`,
60 | },
61 | plugins: [
62 | 'gatsby-plugin-catch-links',
63 | 'gatsby-plugin-react-helmet',
64 | ],
65 | }
66 | ```
67 |
68 | Without any additional work besides a `yarn install` and editing a config file, we now have the ability to edit our site's head tags, as well as implement a single page app feel without reloads. Now let's enhance the base functionality by implementing a source plugin which can load blog posts from our local file system.
69 |
70 | ### Source plugins
71 |
72 | Source plugins create _nodes_ which can then be transformed into a usable format (if not already usable) by a transformer plugin. For instance, a typical workflow often involves using [`gatsby-source-filesystem`][gatsby-source-filesystem], which loads files off of disk--e.g. Markdown files--and then specifying a Markdown transformer to transform the Markdown into HTML.
73 |
74 | Since the bulk of the blog's content, and each article, will be authored in Markdown, let's add that [`gatsby-source-filesystem`][gatsby-source-filesystem] plugin. Similarly to our previous step, we'll install the plugin and then inject into our `gatsby-config.js`, like so:
75 |
76 | ```bash
77 | yarn add gatsby-source-filesystem
78 | ```
79 |
80 | ```javascript{6-12}
81 | module.exports = {
82 | // previous configuration
83 | plugins: [
84 | 'gatsby-plugin-catch-links',
85 | 'gatsby-plugin-react-helmet',
86 | {
87 | resolve: `gatsby-source-filesystem`,
88 | options: {
89 | path: `${__dirname}/src/pages`,
90 | name: 'pages',
91 | },
92 | }
93 | ]
94 | }
95 | ```
96 |
97 | Some explanation will be helpful here! An `options` object can be passed to a plugin, and we're passing the filesystem `path` (i.e. where our Markdown files will be located), and then a `name` for the source files. Now that Gatsby knows about our source files, we can begin applying some useful transformers to convert those files into usable data!
98 |
99 | ### Transformer plugins
100 |
101 | As mentioned, a transformer plugin takes some underlying data format that is not inherently usable in its current form (e.g. Markdown, json, yaml, etc.), and transforms it into a format that Gatsby can understand, and that we can query against with GraphQL. Jointly, the filesystem source plugin will load file nodes (as Markdown) off of our filesystem, and then the Markdown transformer will take over and convert to usable HTML.
102 |
103 | We'll only be using one transformer plugin (for Markdown), so let's get that installed.
104 |
105 | - [gatsby-transformer-remark][gatsby-transformer-remark]
106 | - Uses the [remark][remark] Markdown parser to transform .md files on disk into HTML; additionally this transformer can optionally take plugins to further extend functionality--e.g. add syntax highlighting with `gatsby-remark-prismjs`, `gatsby-remark-copy-linked-files` to copy relative files specified in markdown, `gatsby-remark-images` to compress images and add responsive images with `srcset`, etc.
107 |
108 | The process should be familiar by now, install and then add to config.
109 |
110 | ```bash
111 | yarn add gatsby-transformer-remark
112 | ```
113 |
114 | and editing `gatsby-config.js`
115 |
116 | ```javascript{13-18}
117 | module.exports = {
118 | // previous setup
119 | plugins: [
120 | 'gatsby-plugin-catch-links',
121 | 'gatsby-plugin-react-helmet',
122 | {
123 | resolve: `gatsby-source-filesystem`,
124 | options: {
125 | path: `${__dirname}/src/pages`,
126 | name: 'pages',
127 | },
128 | },
129 | {
130 | resolve: 'gatsby-transformer-remark',
131 | options: {
132 | plugins: [] // just in case those previously mentioned remark plugins sound cool :)
133 | }
134 | },
135 | ]
136 | };
137 | ```
138 |
139 | Whew! Seems like a lot of set up, but collectively these plugins are going to super charge Gatsby, and give us an incredibly powerful (yet relatively simple!) development environment. We have one more set up step and it's an easy one. We're simply going to create a Markdown file that will contain the content of our first blog post. Let's get to it.
140 |
141 | ## Writing our first Markdown blog post
142 |
143 | The `gatsby-source-filesystem` plugin we configured earlier expects our content to be in `src/pages`, so that's exactly where we'll put it!
144 |
145 | Gatsby is not at all prescriptive in naming conventions, but a typical practice for blog posts is to name the folder something like `MM-DD-YYYY-title`, e.g. `07-12-2017-hello-world`. Let's do just that, and create the folder `src/pages/07-12-2017-getting-started`, and place an `index.md` inside!
146 |
147 | The content of this Markdown file will be our blog post, authored in Markdown (of course!). Here's what it'll look like:
148 |
149 | ```markdown
150 | ---
151 | path: "/hello-world"
152 | date: "2017-07-12T17:12:33.962Z"
153 | title: "My First Gatsby Post"
154 | ---
155 |
156 | Oooooh-weeee, my first blog post!
157 |
158 | ```
159 |
160 | _Fairly_ typical stuff, except for the block surrounded in dashes. What is that? That is what is referred to as [`frontmatter`][frontmatter], and the contents of the block can be used to inject React components with the specified data, e.g. path, date, title, etc. Any piece of data can be injected here (e.g. tags, sub-title,draft, etc.), so feel free to experiment and find what necessary pieces of frontmatter are required to achieve an ideal blogging system for your usage. One important note is that `path` will be used when we dynamically create our pages to specify the URL/path to render the file (in a later step!). In this instance, `http://localhost:8000/hello-world` will be the path to this file.
161 |
162 | Now that we have created a blog post with frontmatter and some content, we can begin actually writing some React components that will display this data!
163 |
164 | ## Creating the (React) template
165 |
166 | As Gatsby supports server side rendering (to string) of React components, we can write our template in... you guessed it, React! (Or [Preact][gatsby-plugin-preact], if that's more your style)
167 |
168 | We'll want to create the file `src/templates/blog-post.js` (please create the `src/templates` folder if it does not yet exist!).
169 |
170 | ```javascript
171 | import React from 'react';
172 | import Helmet from 'react-helmet';
173 |
174 | // import '../css/blog-post.css'; // make it pretty!
175 |
176 | export default function Template({
177 | data // this prop will be injected by the GraphQL query we'll write in a bit
178 | }) {
179 | const { markdownRemark: post } = data; // data.markdownRemark holds our post data
180 | return (
181 |
182 |
183 |
184 |
{post.frontmatter.title}
185 |
186 |
187 |
188 | );
189 | }
190 | ```
191 |
192 | Whoa, neat! This React component will be rendered to a static HTML string (for each route/blog post we define), which will serve as the basis of our routing/navigation for our blog.
193 |
194 | At this point, there is a reasonable level of confusion and "magic" occuring, particularly with the props injection. What is `markdownRemark`? Where is this `data` prop injected from? All good questions, so let's answer them by writing a GraphQL query to seed our `` component with content!
195 |
196 | ### Writing the GraphQL query
197 |
198 | Below the `Template` declaration, we'll want to add a GraphQL query. This is an incredibly powerful utility provided by Gatsby which lets us pick and choose very simply the pieces of data that we want to display for our blog post. Each piece of data our query selects will be injected via the `data` property we specified earlier.
199 |
200 | ```javascript{21-32}
201 | import React from 'react';
202 | import Helmet from 'react-helmet';
203 |
204 | // import '../css/blog-post.css';
205 |
206 | export default function Template({
207 | data
208 | }) {
209 | const { markdownRemark: post } = data;
210 | return (
211 |
212 |
213 |
214 |
{post.frontmatter.title}
215 |
216 |
217 |
218 | );
219 | }
220 |
221 | export const pageQuery = graphql`
222 | query BlogPostByPath($path: String!) {
223 | markdownRemark(frontmatter: { path: { eq: $path } }) {
224 | html
225 | frontmatter {
226 | date(formatString: "MMMM DD, YYYY")
227 | path
228 | title
229 | }
230 | }
231 | }
232 | `;
233 | ```
234 |
235 | If you're not familar with GraphQL, this may seem slightly confusing, but we can break down what's going down here piece by piece.
236 |
237 | *Note: To learn more about GraphQL, consider this [excellent resource][learn-graphql]*
238 |
239 | The underlying query name `BlogPostByPath` (note: these query names need to be unique!) will be injected with the current path, e.g. the specific blog post we are viewing. This path will be available as `$path` in our query. For instance, if we were viewing our previously created blog post, the path of the file that data will be pulled from will be `/hello-world`.
240 |
241 | `markdownRemark` will be the injected property available via the prop `data`, as named in the GraphQL query. Each property we pull via the GraphQL query will be available under this `markdownRemark` property. For example, to access the transformed HTML we would access the `data` prop via `data.markdownRemark.html`.
242 |
243 | `frontmatter`, is of course our data structure we provided at the beginning of our Markdown file. Each key we define there will be available to be injected into the query.
244 |
245 | At this point, we have a bunch of plugins installed to load files off of disk, transform Markdown to HTML, and other utilities. We have a single, lonely Markdown file that will be rendered as a blog post. Finally, we have a React template for blog posts, as well as a wired up GraphQL query to query for a blog post and inject the React template with the queried data. Next up: programatically creating the necessary static pages (and injecting the templates) with Gatsby's Node API. Let's get down to it.
246 |
247 | An important note to make at this point is that the GraphQL query takes place at **build** time. The component is injected with the `data` prop that is seeded by the GraphQL query. Unless anything dynamic (e.g. logic in `componentDidMount`, state changes, etc.) occurs, this component will be pure, rendered HTML generated via the React rendering engine, GraphQL, and Gatsby!
248 |
249 | ## Creating the static pages
250 |
251 | Gatsby exposes a powerful Node API, which allows for functionality such as creating dynamic pages (blog posts!), extending the babel or webpack configs, modifying the created nodes or pages, etc. This API is exposed in the `gatsby-node.js` file in the root directory of your project--e.g. at the same level as `gatsby-config.js`. Each export found in this file will be parsed by Gatsby, as detailed in its [Node API specification][node-spec]. However, we only care about one particular API in this instance, `createPages`.
252 |
253 | ```javascript
254 | const path = require('path');
255 |
256 | exports.createPages = ({ boundActionCreators, graphql }) => {
257 | const { createPage } = boundActionCreators;
258 |
259 | const blogPostTemplate = path.resolve(`src/templates/blog-post.js`);
260 | }
261 | ```
262 |
263 | Nothing super complex yet! We're using the `createPages` API (which Gatsby will call at build time with injected parameters). We're also grabbing the _path_ to our blogPostTemplate we created earlier. Finally, we're using the `createPage` action creator/function made available in boundActionCreators. Gatsby uses Redux internally to manage its state, and `boundActionCreators` are simply the exposed action creators of Gatsby, of which `createPage` is one of the action creators! For the full list of exposed action creators, check out [Gatsby's documentation][gatsby-bound-action-creators]. We can now construct the GraphQL query, which will fetch all of our Markdown posts.
264 |
265 | ### Querying for posts
266 |
267 | ```javascript{8-31}
268 | const path = require('path');
269 |
270 | exports.createPages = ({ boundActionCreators, graphql }) => {
271 | const { createPage } = boundActionCreators;
272 |
273 | const blogPostTemplate = path.resolve(`src/templates/blog-post.js`);
274 |
275 | return graphql(`{
276 | allMarkdownRemark(
277 | sort: { order: DESC, fields: [frontmatter___date] }
278 | limit: 1000
279 | ) {
280 | edges {
281 | node {
282 | excerpt(pruneLength: 250)
283 | html
284 | id
285 | frontmatter {
286 | date
287 | path
288 | title
289 | }
290 | }
291 | }
292 | }
293 | }`)
294 | .then(result => {
295 | if (result.errors) {
296 | return Promise.reject(result.errors);
297 | }
298 | });
299 | }
300 | ```
301 |
302 | We're using GraphQL to get all Markdown nodes and making them available under the `allMarkdownRemark` GraphQL property. Each exposed property (on `node`) is made available for querying against. We're effectively seeding a GraphQL "database" that we can then query against via page-level GraphQL queries. One note here is that the `exports.createPages` API expects a Promise to be returned, so it works seamlessly with the `graphql` function, which returns a Promise (although note a callback API is also available if that's more your thing).
303 |
304 | One cool note here is that the `gatsby-plugin-remark` plugin exposes some useful data for us to query with GraphQL, e.g. `excerpt` (a short snippet to display as a preview), `id` (a unique identifier for each post), etc.
305 |
306 | We now have our query written, but we haven't yet programatically created the pages (with the `createPage` action creator). Let's do that!
307 |
308 | ### Creating the pages
309 |
310 | ```javascript{32-39}
311 | const path = require('path');
312 |
313 | exports.createPages = ({ boundActionCreators, graphql }) => {
314 | const { createPage } = boundActionCreators;
315 |
316 | const blogPostTemplate = path.resolve(`src/templates/blog-post.js`);
317 |
318 | return graphql(`{
319 | allMarkdownRemark(
320 | sort: { order: DESC, fields: [frontmatter___date] }
321 | limit: 1000
322 | ) {
323 | edges {
324 | node {
325 | excerpt(pruneLength: 250)
326 | html
327 | id
328 | frontmatter {
329 | date
330 | path
331 | title
332 | }
333 | }
334 | }
335 | }
336 | }`)
337 | .then(result => {
338 | if (result.errors) {
339 | return Promise.reject(result.errors);
340 | }
341 |
342 | result.data.allMarkdownRemark.edges
343 | .forEach(({ node }) => {
344 | createPage({
345 | path: node.frontmatter.path,
346 | component: blogPostTemplate,
347 | context: {} // additional data can be passed via context
348 | });
349 | });
350 | });
351 | }
352 | ```
353 |
354 | We've now tied into the Promise chain exposed by the `graphql` query. The actual posts are available via the path `result.data.allMarkdownRemark.edges`. Each edge contains an internal node, and this node holds the useful data that we will use to construct a page with Gatsby. Our GraphQL "shape" is directly reflected in this data object, so each property we pulled from that query will be available when we are querying in our GraphQL blog post template.
355 |
356 | The `createPage` API accepts an object which requires `path` and `component` properties to be defined, which we have done above. Additionally, an optional property `context` can be used to inject data and make it available to the blog post template component via injected props (log out props to see each available prop!). Each time we build with Gatsby, `createPage` will be called, and Gatsby will create a static HTML file of the path we specified in the post's frontmatter--the result of which will be our stringified and parsed React template injected with the data from our GraphQL query. Whoa, it's actually starting to come together!
357 |
358 | We can run `yarn develop` at this point, and then navigate to `http://localhost:8000/hello-world` to see our first blog post, which should look something like below:
359 |
360 | 
361 |
362 | At this point, we've created a single static blog post as an HTML file, which was created by a React component and several GraphQL queries. However, this isn't a blog! We can't expect our users to guess the path of each post, we need to have an index or listing page, where we display each blog post, a short snippet, and a link to the full blog post. Wouldn't you know it, we can do this incredibly easily with Gatsby, using a similar strategy as we used in our blog template, e.g. a React component and a GraphQL query.
363 |
364 | ## Creating the Blog Listing
365 |
366 | I won't go into quite as much detail for this section, because we've already done something very similar for our blog template! Look at us, we're pro Gatsby-ers at this point!
367 |
368 | Gatsby has a standard for "listing pages," and they're placed in the root of our filesystem we specified in `gatsby-source-filesystem`, e.g. `src/pages/index.js`. So create that file if it does not exist, and let's get it working! Additionally note that any static JavaScript files (that export a React component!) will get a corresponding static HTML file. For instance, if we create `src/pages/tags.js`, the path `http://localhost:8000/tags/` will be available within the browser and the statically generated site.
369 |
370 | ```javascript
371 | import React from 'react';
372 | import Link from 'gatsby-link';
373 | import Helmet from 'react-helmet';
374 |
375 | // import '../css/index.css'; // add some style if you want!
376 |
377 | export default function Index({
378 | data
379 | }) {
380 | const { edges: posts } = data.allMarkdownRemark;
381 | return (
382 |
397 | );
398 | }
399 |
400 | export const pageQuery = graphql`
401 | query IndexQuery {
402 | allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
403 | edges {
404 | node {
405 | excerpt(pruneLength: 250)
406 | id
407 | frontmatter {
408 | title
409 | date(formatString: "MMMM DD, YYYY")
410 | path
411 | }
412 | }
413 | }
414 | }
415 | }
416 | `;
417 | ```
418 |
419 | OK! So we've followed a similar approach to our blog post template, so this should hopefully seem pretty familiar. Once more we're exporting `pageQuery` which contains a GraphQL query. Note that we're pulling a slightly different data set, specifically we are pulling an `excerpt` of 250 characters rather than the full HTML, as well as we are formatting the pulled date with a format string! GraphQL is awesome.
420 |
421 | The actual React component is fairly trivial, but one important note should be made. It's important that when linking to internal content, i.e. other blog links, that you should always use `gatsby-link`. Gatsby does not work if pages are not routed via this utility. Additionally, this utility also works with `pathPrefix`, which allows for a Gatsby site to be deployed a non-root domain. This is useful if this blog will be hosted on something like Github Pages, or perhaps hosted at `/blog`.
422 |
423 | Now this is getting exciting and it feels like we're finally getting somewhere! At this point, we have a fully functional blog generated by Gatsby, with real content authored in Markdown, a blog listing, and the ability to navigate around in the blog. If you run `yarn develop`, `http://localhost:8000` should display a preview of each blog post, and each post title links to the content of the blog post. A real blog!
424 |
425 | 
426 |
427 | It's now on you to make something incredible with the knowledge you've gained in following along with this tutorial! You can not only make it pretty and style with CSS (or [styled-components][styled-components]!), but you could improve it functionally by implementing some of the following:
428 |
429 | - Add a tag listing and tag search page
430 | - hint: the `createPages` API in `gatsby-node.js` file is useful here, as is frontmatter
431 | - adding navigation between a specific blog post and past/present blog posts (the `context` API of `createPages` is useful here), etc.
432 |
433 | With our new found knowledge of Gatsby and its API, you should feel empowered to begin to utilize Gatsby to its fullest potential. A blog is just the starting point; Gatsby's rich ecosystem, extensible API, and advanced querying capabilities provide a powerful toolset for building truly incredible, performant sites.
434 |
435 | Now go build something great.
436 |
437 | 
438 |
439 | ## Links
440 |
441 | - [`@dschau/gatsby-blog-starter-kit`][source-code]
442 | - A working repo demonstrating all of the aforementioned functionality of Gatsby
443 | - [`@dschau/create-gatsby-blog-post`][create-gatsby-blog-post]
444 | - A utility and CLI I created to scaffold out a blog post following the predefined Gatsby structure with frontmatter, date, path, etc.
445 | - [Source code for my blog][blog-source-code]
446 | - The source code for my blog, which takes the gatsby-starter-blog-post (previous link), and expands upon it with a bunch of features and some more advanced functionality
447 |
448 | [react-dom-server]: https://facebook.github.io/react/docs/react-dom-server.html
449 | [gatsby-release]: https://gatsbyjs.org/blog/gatsby-v1/
450 |
451 | [gatsby-plugins]: https://gatsbyjs.org/docs/plugins/
452 |
453 | [gatsby-plugin-catch-links]: https://gatsbyjs.org/packages/gatsby-plugin-catch-links/
454 | [gatsby-plugin-react-helmet]: https://gatsbyjs.org/packages/gatsby-plugin-react-helmet/
455 | [gatsby-plugin-preact]: https://gatsbyjs.org/packages/gatsby-plugin-preact/
456 |
457 | [gatsby-transformer-remark]: /packages/gatsby-transformer-remark/
458 | [remark]: https://github.com/wooorm/remark
459 |
460 | [gatsby-source-filesystem]: /packages/gatsby-source-filesystem/
461 |
462 | [react-helmet]: https://github.com/nfl/react-helmet
463 |
464 | [frontmatter]: https://jekyllrb.com/docs/frontmatter/
465 |
466 | [learn-graphql]: https://www.howtographql.com
467 | [node-spec]: https://gatsbyjs.org/docs/node-apis/
468 | [gatsby-bound-action-creators]: /docs/bound-action-creators/
469 |
470 | [styled-components]: https://github.com/styled-components/styled-components
471 |
472 | [yarn]: https://yarnpkg.com/en/
473 | [source-code]: https://github.com/dschau/gatsby-blog-starter-kit
474 | [blog-source-code]: https://github.com/dschau/blog
475 | [create-gatsby-blog-post]: https://github.com/DSchau/create-gatsby-blog-post
476 |
--------------------------------------------------------------------------------
/__fixtures__/less.md:
--------------------------------------------------------------------------------
1 | ```less
2 | @base: #f938ab;
3 |
4 | .box-shadow(@style, @c) when (iscolor(@c)) {
5 | -webkit-box-shadow: @style @c;
6 | box-shadow: @style @c;
7 | }
8 | .box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
9 | .box-shadow(@style, rgba(0, 0, 0, @alpha));
10 | }
11 | .box {
12 | color: saturate(@base, 5%);
13 | border-color: lighten(@base, 30%);
14 | div { .box-shadow(0 0 5px, 30%) }
15 | }
16 | ```
17 |
--------------------------------------------------------------------------------
/__fixtures__/react.md:
--------------------------------------------------------------------------------
1 | ```javascript
2 | import React from 'react';
3 |
4 | const Heading = (props) =>
16 | )
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/__mocks__/yargs.ts:
--------------------------------------------------------------------------------
1 | export = {
2 | _argv: {
3 | $0: 'prettier-markdown',
4 | _: []
5 | },
6 | get argv() {
7 | return this._argv;
8 | },
9 | set argv(args) {
10 | this._argv = {
11 | ...this._argv,
12 | ...args
13 | };
14 | },
15 | reset() {
16 | this._argv = {
17 | $0: 'prettier-markdown',
18 | _: []
19 | };
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/demo/sample.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DSchau/prettier-markdown/afeed132b17c7226cbcce2452701c10c67bbdb34/demo/sample.gif
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | transform: {
3 | '.(ts|tsx)': '/node_modules/ts-jest/preprocessor.js'
4 | },
5 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts|tsx|js)?$',
6 | moduleFileExtensions: [
7 | 'ts',
8 | 'tsx',
9 | 'js'
10 | ],
11 | testPathIgnorePatterns: [
12 | '/fixtures',
13 | '/node_modules',
14 | '/dist'
15 | ]
16 | }
17 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@dschau/prettier-markdown",
3 | "version": "1.1.2",
4 | "main": "index.js",
5 | "bin": {
6 | "prettier-markdown": "cli.js"
7 | },
8 | "license": "MIT",
9 | "author": "Dustin Schau ",
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/dschau/prettier-markdown"
13 | },
14 | "scripts": {
15 | "prebuild": "npm run clean",
16 | "build": "tsc",
17 | "clean": "del-cli \"dist/**/*\"",
18 | "copy": "cp ./.gitignore dist/.gitignore & cp ./README.md dist/README.md",
19 | "predeploy": "npm run build",
20 | "deploy": "bump-version",
21 | "postdeploy": "npm run copy",
22 | "format": "prettier --single-quote --write \"src/**/*.ts\"",
23 | "test": "jest",
24 | "test:watch": "npm run test -- --watch"
25 | },
26 | "dependencies": {
27 | "figures": "^2.0.0",
28 | "fs-extra": "^4.0.0",
29 | "globby": "~6.1.0",
30 | "prettier": "^1.5.3",
31 | "remark": "~8.0.0",
32 | "unist-util-visit": "^1.1.3",
33 | "yargs": "^8.0.2"
34 | },
35 | "devDependencies": {
36 | "@dschau/bump-version-ci": "^1.0.2",
37 | "@types/jest": "^20.0.4",
38 | "@types/node": "^8.0.14",
39 | "@types/yargs": "^8.0.1",
40 | "del-cli": "^1.1.0",
41 | "jest": "^20.0.4",
42 | "ts-jest": "^20.0.7",
43 | "typescript": "~2.4.2"
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/__tests__/__snapshots__/index.ts.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`it can handle front matter 1`] = `
4 | "---
5 | title: 'Hello World'
6 | tags: [\\"asdf\\", \\"asdf1\\"]
7 | ---
8 |
9 | Some content
10 |
11 | \`\`\`javascript
12 | var a = \\"a\\";
13 |
14 | \`\`\`
15 | "
16 | `;
17 |
18 | exports[`it can handle line highlighting 1`] = `
19 | "\`\`\`typescript{1,2,3-5}
20 | import { Component, OnInit } from \\"@angular/core\\";
21 |
22 | @Component({
23 | selector: \\"sample-hello-world\\",
24 | templateUrl: \\"./hello-world.html\\",
25 | styleUrls: [\\"./hello-world.scss\\"]
26 | })
27 | export default class HelloWorld implements OnInit {
28 | ngOnInit() {
29 | console.log(\\"on init\\");
30 | }
31 | }
32 | \`\`\`
33 | "
34 | `;
35 |
36 | exports[`it handles a complex file 1`] = `
37 | "---
38 | title: Creating a Blog with Gatsby
39 | path: \\"/getting-started-with-gatsby\\"
40 | date: \\"2017-07-17T17:12:33.962Z\\"
41 | tags: [\\"gatsby\\", \\"react\\", \\"javascript\\"]
42 | image: \\"preview.png\\"
43 | excerpt: \\"Gatsby is an incredible static site generator that lets you build a static site that still has all the benefits expected from a modern web application…\\"
44 | ---
45 |
46 | *This blog post was originally published at [Object Partners, Inc.](https://objectpartners.com/2017/07/19/creating-a-static-blog-with-gatsby/), and has since been cross-posted at the [official gatsby blog](https://www.gatsbyjs.org/blog/2017-07-19-creating-a-blog-with-gatsby/)*
47 |
48 | Gatsby is an incredible static site generator that allows for React to be used as the underlying rendering engine to scaffold out a static site that truly has all the benefits expected in a modern web application. It does this by rendering dynamic React components into static HTML content via [server side rendering][react-dom-server] at build time. This means that your users get all the benefits of a static site such as the ability to work without JavaScript, search engine friendliness, speedy load times, etc. without losing the dynamism and interactivity that is expected of the modern web. Once rendered to static HTML, client-site React/JavaScript _can_ take over (if creating stateful components or logic in \`componentDidMount\`) and add dynamism to the statically generated content.
49 |
50 | Gatsby [recently released][gatsby-release] a v1.0.0 with a bunch of new features, including (but not limited to) the ability to create content queries with GraphQL, integration with various CMSs--including WordPress, Contentful, Drupal, etc., and route based code splitting to keep the end-user experience as snappy as possible. In this post, we'll take a deep dive into Gatsby and some of these new features by creating a static blog. Let's get on it!
51 |
52 | ## Getting started
53 |
54 | ### Installing the CLI
55 |
56 | \`npm install -g gatsby\`
57 |
58 | Gatsby ships with a great CLI (command line interface) that contains the functionality of scaffolding out a working site, as well as commands to help develop the site once created.
59 |
60 | \`gatsby new personal-blog && cd $_\`
61 |
62 | This command will create the folder \`personal-blog\` and then change into that directory. A working \`gatsby\` statically generated application can now be developed upon. The Gatsby CLI includes many common development features such as \`gatsby build\` (build a production, statically generated version of the project), \`gatsby develop\` (launch a hot-reload enabled web development server), etc.
63 |
64 | We can now begin the exciting task of *actually* developing on the site, and creating a functional, modern blog. You'll generally want to use \`gatsby develop\` to launch the local development server to validate functionality as we progress through the steps.
65 |
66 | ## Adding necessary plugins
67 |
68 | Gatsby supports a [rich plugin interface][gatsby-plugins], and many incredibly useful plugins have been authored to make accomplishing common tasks a breeze. Plugins can be broken up into three main categories: **functional** plugins, **source** plugins, and **transformer** plugins.
69 |
70 | ### Functional plugins
71 |
72 | Functional plugins either implement some functionality (e.g. offline support, generating a sitemap, etc.) _or_ they extend Gatsby's webpack configuration adding support for typescript, sass, etc.
73 |
74 | For this particular blog post, we want a single page app-like feel (without page reloads), as well as the ability to dynamically change the \`title\` tag within the \`head\` tags. As noted, the Gatsby plugin ecosystem is rich, vibrant, and growing, so oftentimes a plugin already exists that solves the particular problem you're trying to solve. To address the functionality we want for _this_ blog, we'll use the following plugins:
75 |
76 | - [\`gatsby-plugin-catch-links\`][gatsby-plugin-catch-links]
77 | - implements the history \`pushState\` API, and does not require a page reload on navigating to a different page in the blog
78 | - [\`gatsby-plugin-react-helmet\`][gatsby-plugin-react-helmet]
79 | - [react-helmet][react-helmet] is a tool that allows for modification of the \`head\` tags; Gatsby statically renders any of these \`head\` tag changes
80 |
81 | with the following command:
82 |
83 | \`\`\`bash
84 | yarn add gatsby-plugin-catch-links gatsby-plugin-react-helmet
85 | \`\`\`
86 |
87 | We're using [yarn][yarn], but npm can just as easily be used with \`npm i --save [deps]\`.
88 |
89 | After installing each of these functional plugins, we'll edit \`gatsby-config.js\`, which Gatsby loads at build-time to implement the exposed functionality of the specified plugins.
90 |
91 | \`\`\`javascript{6-9}
92 | module.exports = {
93 | siteMetadata: {
94 | title: \`Your Name - Blog\`,
95 | author: \`Your Name\`
96 | },
97 | plugins: [\\"gatsby-plugin-catch-links\\", \\"gatsby-plugin-react-helmet\\"]
98 | };
99 | \`\`\`
100 |
101 | Without any additional work besides a \`yarn install\` and editing a config file, we now have the ability to edit our site's head tags, as well as implement a single page app feel without reloads. Now let's enhance the base functionality by implementing a source plugin which can load blog posts from our local file system.
102 |
103 | ### Source plugins
104 |
105 | Source plugins create _nodes_ which can then be transformed into a usable format (if not already usable) by a transformer plugin. For instance, a typical workflow often involves using [\`gatsby-source-filesystem\`][gatsby-source-filesystem], which loads files off of disk--e.g. Markdown files--and then specifying a Markdown transformer to transform the Markdown into HTML.
106 |
107 | Since the bulk of the blog's content, and each article, will be authored in Markdown, let's add that [\`gatsby-source-filesystem\`][gatsby-source-filesystem] plugin. Similarly to our previous step, we'll install the plugin and then inject into our \`gatsby-config.js\`, like so:
108 |
109 | \`\`\`bash
110 | yarn add gatsby-source-filesystem
111 | \`\`\`
112 |
113 | \`\`\`javascript{6-12}
114 | module.exports = {
115 | // previous configuration
116 | plugins: [
117 | \\"gatsby-plugin-catch-links\\",
118 | \\"gatsby-plugin-react-helmet\\",
119 | {
120 | resolve: \`gatsby-source-filesystem\`,
121 | options: {
122 | path: \`\${__dirname}/src/pages\`,
123 | name: \\"pages\\"
124 | }
125 | }
126 | ]
127 | };
128 | \`\`\`
129 |
130 | Some explanation will be helpful here! An \`options\` object can be passed to a plugin, and we're passing the filesystem \`path\` (i.e. where our Markdown files will be located), and then a \`name\` for the source files. Now that Gatsby knows about our source files, we can begin applying some useful transformers to convert those files into usable data!
131 |
132 | ### Transformer plugins
133 |
134 | As mentioned, a transformer plugin takes some underlying data format that is not inherently usable in its current form (e.g. Markdown, json, yaml, etc.), and transforms it into a format that Gatsby can understand, and that we can query against with GraphQL. Jointly, the filesystem source plugin will load file nodes (as Markdown) off of our filesystem, and then the Markdown transformer will take over and convert to usable HTML.
135 |
136 | We'll only be using one transformer plugin (for Markdown), so let's get that installed.
137 |
138 | - [gatsby-transformer-remark][gatsby-transformer-remark]
139 | - Uses the [remark][remark] Markdown parser to transform .md files on disk into HTML; additionally this transformer can optionally take plugins to further extend functionality--e.g. add syntax highlighting with \`gatsby-remark-prismjs\`, \`gatsby-remark-copy-linked-files\` to copy relative files specified in markdown, \`gatsby-remark-images\` to compress images and add responsive images with \`srcset\`, etc.
140 |
141 | The process should be familiar by now, install and then add to config.
142 |
143 | \`\`\`bash
144 | yarn add gatsby-transformer-remark
145 | \`\`\`
146 |
147 | and editing \`gatsby-config.js\`
148 |
149 | \`\`\`javascript{13-18}
150 | module.exports = {
151 | // previous setup
152 | plugins: [
153 | \\"gatsby-plugin-catch-links\\",
154 | \\"gatsby-plugin-react-helmet\\",
155 | {
156 | resolve: \`gatsby-source-filesystem\`,
157 | options: {
158 | path: \`\${__dirname}/src/pages\`,
159 | name: \\"pages\\"
160 | }
161 | },
162 | {
163 | resolve: \\"gatsby-transformer-remark\\",
164 | options: {
165 | plugins: [] // just in case those previously mentioned remark plugins sound cool :)
166 | }
167 | }
168 | ]
169 | };
170 | \`\`\`
171 |
172 | Whew! Seems like a lot of set up, but collectively these plugins are going to super charge Gatsby, and give us an incredibly powerful (yet relatively simple!) development environment. We have one more set up step and it's an easy one. We're simply going to create a Markdown file that will contain the content of our first blog post. Let's get to it.
173 |
174 | ## Writing our first Markdown blog post
175 |
176 | The \`gatsby-source-filesystem\` plugin we configured earlier expects our content to be in \`src/pages\`, so that's exactly where we'll put it!
177 |
178 | Gatsby is not at all prescriptive in naming conventions, but a typical practice for blog posts is to name the folder something like \`MM-DD-YYYY-title\`, e.g. \`07-12-2017-hello-world\`. Let's do just that, and create the folder \`src/pages/07-12-2017-getting-started\`, and place an \`index.md\` inside!
179 |
180 | The content of this Markdown file will be our blog post, authored in Markdown (of course!). Here's what it'll look like:
181 |
182 | \`\`\`markdown
183 | ---
184 | path: \\"/hello-world\\"
185 | date: \\"2017-07-12T17:12:33.962Z\\"
186 | title: \\"My First Gatsby Post\\"
187 | ---
188 |
189 | Oooooh-weeee, my first blog post!
190 |
191 | \`\`\`
192 |
193 | _Fairly_ typical stuff, except for the block surrounded in dashes. What is that? That is what is referred to as [\`frontmatter\`][frontmatter], and the contents of the block can be used to inject React components with the specified data, e.g. path, date, title, etc. Any piece of data can be injected here (e.g. tags, sub-title,draft, etc.), so feel free to experiment and find what necessary pieces of frontmatter are required to achieve an ideal blogging system for your usage. One important note is that \`path\` will be used when we dynamically create our pages to specify the URL/path to render the file (in a later step!). In this instance, \`http://localhost:8000/hello-world\` will be the path to this file.
194 |
195 | Now that we have created a blog post with frontmatter and some content, we can begin actually writing some React components that will display this data!
196 |
197 | ## Creating the (React) template
198 |
199 | As Gatsby supports server side rendering (to string) of React components, we can write our template in... you guessed it, React! (Or [Preact][gatsby-plugin-preact], if that's more your style)
200 |
201 | We'll want to create the file \`src/templates/blog-post.js\` (please create the \`src/templates\` folder if it does not yet exist!).
202 |
203 | \`\`\`javascript
204 | import React from \\"react\\";
205 | import Helmet from \\"react-helmet\\";
206 |
207 | // import '../css/blog-post.css'; // make it pretty!
208 |
209 | export default function Template({
210 | data // this prop will be injected by the GraphQL query we'll write in a bit
211 | }) {
212 | const { markdownRemark: post } = data; // data.markdownRemark holds our post data
213 | return (
214 |
215 |
216 |
217 |
218 | {post.frontmatter.title}
219 |
220 |
224 |
225 |
226 | );
227 | }
228 | \`\`\`
229 |
230 | Whoa, neat! This React component will be rendered to a static HTML string (for each route/blog post we define), which will serve as the basis of our routing/navigation for our blog.
231 |
232 | At this point, there is a reasonable level of confusion and \\"magic\\" occuring, particularly with the props injection. What is \`markdownRemark\`? Where is this \`data\` prop injected from? All good questions, so let's answer them by writing a GraphQL query to seed our \`\` component with content!
233 |
234 | ### Writing the GraphQL query
235 |
236 | Below the \`Template\` declaration, we'll want to add a GraphQL query. This is an incredibly powerful utility provided by Gatsby which lets us pick and choose very simply the pieces of data that we want to display for our blog post. Each piece of data our query selects will be injected via the \`data\` property we specified earlier.
237 |
238 | \`\`\`javascript{21-32}
239 | import React from \\"react\\";
240 | import Helmet from \\"react-helmet\\";
241 |
242 | // import '../css/blog-post.css';
243 |
244 | export default function Template({ data }) {
245 | const { markdownRemark: post } = data;
246 | return (
247 |
248 |
249 |
250 |
251 | {post.frontmatter.title}
252 |
253 |
257 |
258 |
259 | );
260 | }
261 |
262 | export const pageQuery = graphql\`
263 | query BlogPostByPath($path: String!) {
264 | markdownRemark(frontmatter: { path: { eq: $path } }) {
265 | html
266 | frontmatter {
267 | date(formatString: \\"MMMM DD, YYYY\\")
268 | path
269 | title
270 | }
271 | }
272 | }
273 | \`;
274 | \`\`\`
275 |
276 | If you're not familar with GraphQL, this may seem slightly confusing, but we can break down what's going down here piece by piece.
277 |
278 | *Note: To learn more about GraphQL, consider this [excellent resource][learn-graphql]*
279 |
280 | The underlying query name \`BlogPostByPath\` (note: these query names need to be unique!) will be injected with the current path, e.g. the specific blog post we are viewing. This path will be available as \`$path\` in our query. For instance, if we were viewing our previously created blog post, the path of the file that data will be pulled from will be \`/hello-world\`.
281 |
282 | \`markdownRemark\` will be the injected property available via the prop \`data\`, as named in the GraphQL query. Each property we pull via the GraphQL query will be available under this \`markdownRemark\` property. For example, to access the transformed HTML we would access the \`data\` prop via \`data.markdownRemark.html\`.
283 |
284 | \`frontmatter\`, is of course our data structure we provided at the beginning of our Markdown file. Each key we define there will be available to be injected into the query.
285 |
286 | At this point, we have a bunch of plugins installed to load files off of disk, transform Markdown to HTML, and other utilities. We have a single, lonely Markdown file that will be rendered as a blog post. Finally, we have a React template for blog posts, as well as a wired up GraphQL query to query for a blog post and inject the React template with the queried data. Next up: programatically creating the necessary static pages (and injecting the templates) with Gatsby's Node API. Let's get down to it.
287 |
288 | An important note to make at this point is that the GraphQL query takes place at **build** time. The component is injected with the \`data\` prop that is seeded by the GraphQL query. Unless anything dynamic (e.g. logic in \`componentDidMount\`, state changes, etc.) occurs, this component will be pure, rendered HTML generated via the React rendering engine, GraphQL, and Gatsby!
289 |
290 | ## Creating the static pages
291 |
292 | Gatsby exposes a powerful Node API, which allows for functionality such as creating dynamic pages (blog posts!), extending the babel or webpack configs, modifying the created nodes or pages, etc. This API is exposed in the \`gatsby-node.js\` file in the root directory of your project--e.g. at the same level as \`gatsby-config.js\`. Each export found in this file will be parsed by Gatsby, as detailed in its [Node API specification][node-spec]. However, we only care about one particular API in this instance, \`createPages\`.
293 |
294 | \`\`\`javascript
295 | const path = require(\\"path\\");
296 |
297 | exports.createPages = ({ boundActionCreators, graphql }) => {
298 | const { createPage } = boundActionCreators;
299 |
300 | const blogPostTemplate = path.resolve(\`src/templates/blog-post.js\`);
301 | };
302 | \`\`\`
303 |
304 | Nothing super complex yet! We're using the \`createPages\` API (which Gatsby will call at build time with injected parameters). We're also grabbing the _path_ to our blogPostTemplate we created earlier. Finally, we're using the \`createPage\` action creator/function made available in boundActionCreators. Gatsby uses Redux internally to manage its state, and \`boundActionCreators\` are simply the exposed action creators of Gatsby, of which \`createPage\` is one of the action creators! For the full list of exposed action creators, check out [Gatsby's documentation][gatsby-bound-action-creators]. We can now construct the GraphQL query, which will fetch all of our Markdown posts.
305 |
306 | ### Querying for posts
307 |
308 | \`\`\`javascript{8-31}
309 | const path = require(\\"path\\");
310 |
311 | exports.createPages = ({ boundActionCreators, graphql }) => {
312 | const { createPage } = boundActionCreators;
313 |
314 | const blogPostTemplate = path.resolve(\`src/templates/blog-post.js\`);
315 |
316 | return graphql(\`{
317 | allMarkdownRemark(
318 | sort: { order: DESC, fields: [frontmatter___date] }
319 | limit: 1000
320 | ) {
321 | edges {
322 | node {
323 | excerpt(pruneLength: 250)
324 | html
325 | id
326 | frontmatter {
327 | date
328 | path
329 | title
330 | }
331 | }
332 | }
333 | }
334 | }\`).then(result => {
335 | if (result.errors) {
336 | return Promise.reject(result.errors);
337 | }
338 | });
339 | };
340 | \`\`\`
341 |
342 | We're using GraphQL to get all Markdown nodes and making them available under the \`allMarkdownRemark\` GraphQL property. Each exposed property (on \`node\`) is made available for querying against. We're effectively seeding a GraphQL \\"database\\" that we can then query against via page-level GraphQL queries. One note here is that the \`exports.createPages\` API expects a Promise to be returned, so it works seamlessly with the \`graphql\` function, which returns a Promise (although note a callback API is also available if that's more your thing).
343 |
344 | One cool note here is that the \`gatsby-plugin-remark\` plugin exposes some useful data for us to query with GraphQL, e.g. \`excerpt\` (a short snippet to display as a preview), \`id\` (a unique identifier for each post), etc.
345 |
346 | We now have our query written, but we haven't yet programatically created the pages (with the \`createPage\` action creator). Let's do that!
347 |
348 | ### Creating the pages
349 |
350 | \`\`\`javascript{32-39}
351 | const path = require(\\"path\\");
352 |
353 | exports.createPages = ({ boundActionCreators, graphql }) => {
354 | const { createPage } = boundActionCreators;
355 |
356 | const blogPostTemplate = path.resolve(\`src/templates/blog-post.js\`);
357 |
358 | return graphql(\`{
359 | allMarkdownRemark(
360 | sort: { order: DESC, fields: [frontmatter___date] }
361 | limit: 1000
362 | ) {
363 | edges {
364 | node {
365 | excerpt(pruneLength: 250)
366 | html
367 | id
368 | frontmatter {
369 | date
370 | path
371 | title
372 | }
373 | }
374 | }
375 | }
376 | }\`).then(result => {
377 | if (result.errors) {
378 | return Promise.reject(result.errors);
379 | }
380 |
381 | result.data.allMarkdownRemark.edges.forEach(({ node }) => {
382 | createPage({
383 | path: node.frontmatter.path,
384 | component: blogPostTemplate,
385 | context: {} // additional data can be passed via context
386 | });
387 | });
388 | });
389 | };
390 | \`\`\`
391 |
392 | We've now tied into the Promise chain exposed by the \`graphql\` query. The actual posts are available via the path \`result.data.allMarkdownRemark.edges\`. Each edge contains an internal node, and this node holds the useful data that we will use to construct a page with Gatsby. Our GraphQL \\"shape\\" is directly reflected in this data object, so each property we pulled from that query will be available when we are querying in our GraphQL blog post template.
393 |
394 | The \`createPage\` API accepts an object which requires \`path\` and \`component\` properties to be defined, which we have done above. Additionally, an optional property \`context\` can be used to inject data and make it available to the blog post template component via injected props (log out props to see each available prop!). Each time we build with Gatsby, \`createPage\` will be called, and Gatsby will create a static HTML file of the path we specified in the post's frontmatter--the result of which will be our stringified and parsed React template injected with the data from our GraphQL query. Whoa, it's actually starting to come together!
395 |
396 | We can run \`yarn develop\` at this point, and then navigate to \`http://localhost:8000/hello-world\` to see our first blog post, which should look something like below:
397 |
398 | 
399 |
400 | At this point, we've created a single static blog post as an HTML file, which was created by a React component and several GraphQL queries. However, this isn't a blog! We can't expect our users to guess the path of each post, we need to have an index or listing page, where we display each blog post, a short snippet, and a link to the full blog post. Wouldn't you know it, we can do this incredibly easily with Gatsby, using a similar strategy as we used in our blog template, e.g. a React component and a GraphQL query.
401 |
402 | ## Creating the Blog Listing
403 |
404 | I won't go into quite as much detail for this section, because we've already done something very similar for our blog template! Look at us, we're pro Gatsby-ers at this point!
405 |
406 | Gatsby has a standard for \\"listing pages,\\" and they're placed in the root of our filesystem we specified in \`gatsby-source-filesystem\`, e.g. \`src/pages/index.js\`. So create that file if it does not exist, and let's get it working! Additionally note that any static JavaScript files (that export a React component!) will get a corresponding static HTML file. For instance, if we create \`src/pages/tags.js\`, the path \`http://localhost:8000/tags/\` will be available within the browser and the statically generated site.
407 |
408 | \`\`\`javascript
409 | import React from \\"react\\";
410 | import Link from \\"gatsby-link\\";
411 | import Helmet from \\"react-helmet\\";
412 |
413 | // import '../css/index.css'; // add some style if you want!
414 |
415 | export default function Index({ data }) {
416 | const { edges: posts } = data.allMarkdownRemark;
417 | return (
418 |
439 | );
440 | }
441 |
442 | export const pageQuery = graphql\`
443 | query IndexQuery {
444 | allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
445 | edges {
446 | node {
447 | excerpt(pruneLength: 250)
448 | id
449 | frontmatter {
450 | title
451 | date(formatString: \\"MMMM DD, YYYY\\")
452 | path
453 | }
454 | }
455 | }
456 | }
457 | }
458 | \`;
459 | \`\`\`
460 |
461 | OK! So we've followed a similar approach to our blog post template, so this should hopefully seem pretty familiar. Once more we're exporting \`pageQuery\` which contains a GraphQL query. Note that we're pulling a slightly different data set, specifically we are pulling an \`excerpt\` of 250 characters rather than the full HTML, as well as we are formatting the pulled date with a format string! GraphQL is awesome.
462 |
463 | The actual React component is fairly trivial, but one important note should be made. It's important that when linking to internal content, i.e. other blog links, that you should always use \`gatsby-link\`. Gatsby does not work if pages are not routed via this utility. Additionally, this utility also works with \`pathPrefix\`, which allows for a Gatsby site to be deployed a non-root domain. This is useful if this blog will be hosted on something like Github Pages, or perhaps hosted at \`/blog\`.
464 |
465 | Now this is getting exciting and it feels like we're finally getting somewhere! At this point, we have a fully functional blog generated by Gatsby, with real content authored in Markdown, a blog listing, and the ability to navigate around in the blog. If you run \`yarn develop\`, \`http://localhost:8000\` should display a preview of each blog post, and each post title links to the content of the blog post. A real blog!
466 |
467 | 
468 |
469 | It's now on you to make something incredible with the knowledge you've gained in following along with this tutorial! You can not only make it pretty and style with CSS (or [styled-components][styled-components]!), but you could improve it functionally by implementing some of the following:
470 |
471 | - Add a tag listing and tag search page
472 | - hint: the \`createPages\` API in \`gatsby-node.js\` file is useful here, as is frontmatter
473 | - adding navigation between a specific blog post and past/present blog posts (the \`context\` API of \`createPages\` is useful here), etc.
474 |
475 | With our new found knowledge of Gatsby and its API, you should feel empowered to begin to utilize Gatsby to its fullest potential. A blog is just the starting point; Gatsby's rich ecosystem, extensible API, and advanced querying capabilities provide a powerful toolset for building truly incredible, performant sites.
476 |
477 | Now go build something great.
478 |
479 | 
480 |
481 | ## Links
482 |
483 | - [\`@dschau/gatsby-blog-starter-kit\`][source-code]
484 | - A working repo demonstrating all of the aforementioned functionality of Gatsby
485 | - [\`@dschau/create-gatsby-blog-post\`][create-gatsby-blog-post]
486 | - A utility and CLI I created to scaffold out a blog post following the predefined Gatsby structure with frontmatter, date, path, etc.
487 | - [Source code for my blog][blog-source-code]
488 | - The source code for my blog, which takes the gatsby-starter-blog-post (previous link), and expands upon it with a bunch of features and some more advanced functionality
489 |
490 | [react-dom-server]: https://facebook.github.io/react/docs/react-dom-server.html
491 | [gatsby-release]: https://gatsbyjs.org/blog/gatsby-v1/
492 |
493 | [gatsby-plugins]: https://gatsbyjs.org/docs/plugins/
494 |
495 | [gatsby-plugin-catch-links]: https://gatsbyjs.org/packages/gatsby-plugin-catch-links/
496 | [gatsby-plugin-react-helmet]: https://gatsbyjs.org/packages/gatsby-plugin-react-helmet/
497 | [gatsby-plugin-preact]: https://gatsbyjs.org/packages/gatsby-plugin-preact/
498 |
499 | [gatsby-transformer-remark]: /packages/gatsby-transformer-remark/
500 | [remark]: https://github.com/wooorm/remark
501 |
502 | [gatsby-source-filesystem]: /packages/gatsby-source-filesystem/
503 |
504 | [react-helmet]: https://github.com/nfl/react-helmet
505 |
506 | [frontmatter]: https://jekyllrb.com/docs/frontmatter/
507 |
508 | [learn-graphql]: https://www.howtographql.com
509 | [node-spec]: https://gatsbyjs.org/docs/node-apis/
510 | [gatsby-bound-action-creators]: /docs/bound-action-creators/
511 |
512 | [styled-components]: https://github.com/styled-components/styled-components
513 |
514 | [yarn]: https://yarnpkg.com/en/
515 | [source-code]: https://github.com/dschau/gatsby-blog-starter-kit
516 | [blog-source-code]: https://github.com/dschau/blog
517 | [create-gatsby-blog-post]: https://github.com/DSchau/create-gatsby-blog-post
518 | "
519 | `;
520 |
521 | exports[`it makes CSS prettier 1`] = `
522 | "\`\`\`css
523 | p {
524 | color: red;
525 | }
526 |
527 | body {
528 | font-family: 'Georgia', sans-serif;
529 | }
530 |
531 | \`\`\`
532 | "
533 | `;
534 |
535 | exports[`it makes GraphQL prettier 1`] = `
536 | "\`\`\`graphql
537 | {
538 | empireHero: hero(episode: EMPIRE) {
539 | name
540 | }
541 | jediHero: hero(episode: JEDI) {
542 | name
543 | }
544 | }
545 | \`\`\`
546 | "
547 | `;
548 |
549 | exports[`it makes JSON prettier 1`] = `
550 | "\`\`\`json
551 | {
552 | \\"asdf\\": \\"asdf\\",
553 |
554 | \\"value\\": true,
555 |
556 | \\"other_value\\": false
557 | }
558 | \`\`\`
559 | "
560 | `;
561 |
562 | exports[`it makes LESS prettier 1`] = `
563 | "\`\`\`less
564 | @base: #f938ab;
565 |
566 | .box-shadow(@style, @c) when (iscolor(@c)) {
567 | -webkit-box-shadow: @style @c;
568 | box-shadow: @style @c;
569 | }
570 | .box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
571 | .box-shadow(@style, rgba(0, 0, 0, @alpha));
572 | }
573 | .box {
574 | color: saturate(@base, 5%);
575 | border-color: lighten(@base, 30%);
576 | div {
577 | .box-shadow(0 0 5px, 30%);
578 | }
579 | }
580 | \`\`\`
581 | "
582 | `;
583 |
584 | exports[`it makes SCSS prettier 1`] = `
585 | "\`\`\`scss
586 | $color: red;
587 |
588 | @mixin generateContent( $otherColor: $color ) {
589 | background-color: $otherColor;
590 | }
591 |
592 | body {
593 | @include generateContent();
594 | }
595 |
596 | \`\`\`
597 | "
598 | `;
599 |
600 | exports[`it makes a simple JSX snippet prettier 1`] = `
601 | "\`\`\`javascript
602 | import React from \\"react\\";
603 |
604 | const Heading = props =>
605 |