DEV Community

Katie Liu
Katie Liu

Posted on

Exploring the code behind Docusaurus

This week I want to add a new feature to my text to HTML converter, go-go-web. The feature I plan to add is Markdown Front Matter support. When a user converts an .md file to .html using my program, my program would be able to convert Front Matter in the .md file into metadata tag content in the resulting .html file.

What is Front Matter?

Front matter is a bit of text at the start of a file (YAML to be exact) that is placed between two ---

Example of an .md file with Front Matter:

---
title: My First Blog
lang: en
description: This is my first ever blog about programming.
keywords: website, coding
---

This is where the blog content paragraphs go.
Enter fullscreen mode Exit fullscreen mode

Learning from Docusaurus

This time, instead of starting to implement this right away, I decided to check out how Docusaurus does it, and try to employ similar methods.

Docusaurus is an open source Static Site Generator built with React. It simplifies the process of creating and maintaining user-friendly, customizable documentation websites.

I know that Docusaurus supports Markdown front matter, and that its license allows for the code to be used and copied. Thus, I decided to use GitHub Code Search in its repo to find out how it is parsing the Markdown front matter.

GitHub Search frontmatter

After reading through the search results, I came across a function that has a name that matches the functionality I was searching for, parseFrontMatter. It is also inside a file called markdownUtils.ts so I know that this is meant for Markdown files.

parseFrontMatter method

After skimming through the file, here are the key lines of code I have identified which implements the markdown front matter parsing I was looking for.

Image description

Image description

It turns out that Docusaurus uses an open source JavaScript parser called gray-matter to parse the front matter from markdown files! After installing gray-matter using npm and them importing it into the markdownUtils.ts file, all it takes is calling the matter method and passing the markdown file contents to get returned an Object with data and content (the data being the front matter and the content being the rest of the markdown file contents).

Here is an example from the gray-matter documentation:

Image description

As you can see, after using gray-matter to parse the markdown file contents, all the front matter is stored in the data object in key-value pairs, making them easy to access.

Now that I have studied how Docusaurus implemented front matter parsing, I learned that it is more efficient to use an open source parser such as gray-matter rather than try to build the parser from scratch. In my python implementation, I will search for a similar parser in python and use it to implement my new feature.

Top comments (0)