DEV Community

Cover image for Parse Markdown Frontmatter In MDX, Remark, and Unified
Minh-Phuc Tran
Minh-Phuc Tran

Posted on • Edited on • Originally published at phuctm97.com

4 3

Parse Markdown Frontmatter In MDX, Remark, and Unified

Today I created a small Unified/Remark plugin called remark-parse-frontmatter to help easily parse frontmatter in a Markdown or MDX document using either mdxjs or remarkjs or unifiedjs.

In case you don't know what is Unified/Remark is, Unified provides an interface for processing content like Markdown, HTML, JSX, etc, in an extremly modular design which allows writing and using plugins easy (but sometimes also feel a bit fragmented).

What is frontmatter in Markdown?

Frontmatter is the first block in a Markdown document that starts and ends with a line ---. Frontmatter defines a Markdown document's metadata.

For example, this is the frontmatter of this article you're reading:

---
title: Parse Markdown Frontmatter In MDX, Remark, and Unified
description: >-
  Leverage Unified/Remark plugin ecosystem to easily parse frontmatter in your
  Markdown or MDX documents.
tags: [markdown, javascript, react, plugin]
published time: 2020-12-25
---
Enter fullscreen mode Exit fullscreen mode

Markdown frontmatter is supported by Github and most popular code editors which help writing and maintaining them more fun.

Parse frontmatter with remark-parse-frontmatter

remark-parse-frontmatter provides 2 essential features when working with frontmatter:

  • Parses the YAML content of a markdown and turns that into a JavaScript object for usage.

  • Validates the object using revalidator.

This plugin requires plugin remark-frontmatter to be applied first (which reads the text and turns into a syntax tree, not a JSON object, and has no validation).

const processor = remark()
  .use(require("remark-frontmatter"))
  .use(require("remark-parse-frontmatter"))
  .freeze();

const file = processor.processSync(`
---
title: Hello, World!
---
`);

console.log(file.data.frontmatter);
Enter fullscreen mode Exit fullscreen mode

⬇️

{
  title: "Hello, World!"
}
Enter fullscreen mode Exit fullscreen mode

Remember to first install the plugin:

yarn add remark-parse-frontmatter
Enter fullscreen mode Exit fullscreen mode

Check out the NPM package and the plugin's repository for more details.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay