mdast-util-frontmatter

mdast extension to parse and serialize frontmatter (YAML, TOML, etc)

Usage no npm install needed!

<script type="module">
  import mdastUtilFrontmatter from 'https://cdn.skypack.dev/mdast-util-frontmatter';
</script>

README

mdast-util-frontmatter

Build Coverage Downloads Size Sponsors Backers Chat

Extension for mdast-util-from-markdown and/or mdast-util-to-markdown to support frontmatter in mdast. When parsing (from-markdown), must be combined with micromark-extension-frontmatter.

When to use this

Use this if you’re dealing with the AST manually. It’s probably nicer to use remark-frontmatter with remark, which includes this but provides a nicer interface and makes it easier to combine with hundreds of plugins.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install mdast-util-frontmatter

Use

Say we have the following file, example.md:

+++
title = "New Website"
+++

# Other markdown

And our module, example.js, looks as follows:

import fs from 'node:fs'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toMarkdown} from 'mdast-util-to-markdown'
import {frontmatter} from 'micromark-extension-frontmatter'
import {frontmatterFromMarkdown, frontmatterToMarkdown} from 'mdast-util-frontmatter'

const doc = fs.readFileSync('example.md')

const tree = fromMarkdown(doc, {
  extensions: [frontmatter(['yaml', 'toml'])],
  mdastExtensions: [frontmatterFromMarkdown(['yaml', 'toml'])]
})

console.log(tree)

const out = toMarkdown(tree, {extensions: [frontmatterToMarkdown(['yaml', 'toml'])]})

console.log(out)

Now, running node example yields:

{
  type: 'root',
  children: [
    {type: 'toml', value: 'title = "New Website"'},
    {
      type: 'heading',
      depth: 1,
      children: [{type: 'text', value: 'Other markdown'}]
    }
  ]
}
+++
title = "New Website"
+++

# Other markdown

API

This package exports the following identifiers: frontmatterFromMarkdown, frontmatterToMarkdown. There is no default export.

frontmatterFromMarkdown([options])

frontmatterToMarkdown([options])

Support frontmatter (YAML, TOML, and more). These functions can be called with options and return extensions, respectively for mdast-util-from-markdown and mdast-util-to-markdown.

Options are the same as micromark-extension-frontmatter.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer