How to access the frontmatter using remark-frontmatter?
Asked Answered
A

2

6

I am trying to use the remarkjs ecosystem to parse a file containing markdown and frontmatter, and turn it into HTML. The file could look something like this:

---
title: Title
---

# This is a heading

I managed to parse the markdown, which can be done by following the example in the GitHub README file, and I also know that there is a remark-frontmatter package. However, just using the package like in the before-mentioned example makes it so the parser ignores the frontmatter part entirely. Of course that part shouldn't be included in the HTML, but I still want to use it. But as far as I can tell, it is not part of the output. That brings me to my question: How can I access the frontmatter using these packages? I know that it is being parsed somewhere in the process, but how can I access this?

Antifebrile answered 20/10, 2022 at 19:54 Comment(0)
P
10

I found the docs to be very confusing, because the most common use-case of the remarkFrontmatter plugin should be to make the frontmatter accessible in the file. However, it doesn't do this, and one has to install remarkParseFrontmatter to get that functionality.

Here are a couple of working versions. One is with Unified, and one is with Remark.

import { unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkFrontmatter from 'remark-frontmatter'
import remarkParseFrontmatter from 'remark-parse-frontmatter'
import remarkStringify from 'remark-stringify'
import { remark } from 'remark';

// With Unified, which is a lower-level API that remark uses internally.

const fileOfUnified = unified()
  .use(remarkParse)
  .use(remarkStringify)
  .use(remarkFrontmatter, ['yaml', 'toml'])
  .use(remarkParseFrontmatter)
  .processSync(`---\ntitle: unified worked\n---`)

console.log(fileOfUnified.data.frontmatter); // {title: 'unified worked'}

// With Remark, which is built on top of Unified, basically by adding remarkParse and remarkStringify.

const fileOfRemark = remark()
  .use(remarkFrontmatter, ['yaml', 'toml'])
  .use(remarkParseFrontmatter)
  .processSync(`---\ntitle: remark worked\n---`)

console.log(fileOfRemark.data.frontmatter); // {title: 'remark worked'}
Prunella answered 6/11, 2022 at 21:34 Comment(1)
remarkParseFrontmatter is deprecated. Ended using gray-matterLowland
A
2

I found that if you do:

add a name property, like what is shown in the doc:

remarkPlugins: [remarkFrontmatter, [remarkMdxFrontmatter, {name: 'matter'}]]

You can get the front matter by file.matter.

It seems the name can be anything except for the keyword frontMatter -- I tried matter, frontM, etc. All works, but frontmatter will not work on my side.

Not sure if this is a bug.

Arbela answered 23/8, 2023 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.