Store Heading Metadata in a Markdown Document with remark

John Otander
InstructorJohn Otander
Share this video with your friends

Social Share Links

Send Tweet

You can use unified's virtual file to add data from a document in order to use it elsewhere. In this lesson we'll store metadata from all heading nodes in a markdown document using remark and vfile.

Instructor: [00:00] First, we're going to begin with our test. We'll also want to open up the fixture file so we can look at our headings that we'll expect in our result.

[00:07] Remark will return a data object as part of the result. We can de-structure the headings from there, which you can then assert against in our test.

[00:15] With the test written, you can run yarn test to make sure that it fails. Now we can begin implementing our plugin. In addition to our tree, we'll also pass a virtual file from remark.

[00:25] This is what we're taking the headings from so we can also use that in our plugin. To start, we'll add some mock data. We can run our test again to make sure our mock data is being returned.

[00:35] Now, it's time to actually visit our heading nodes so we can yarn add unist-util-visit. We can then require the library and then use that by passing at the tree and selecting all heading nodes.

[00:47] To start, we can take the depth from each heading node. On the file object, we need to set the default for headings and the data, and then push the depth as a key in the object. We can run our test again and see the proper depth being added to our data attribute.

[01:00] From within our heading node, we'll also need to visit the text nodes. We'll also instantiate a text string which we'll add to for each of the text nodes that we visit. Lastly, we can add the text to our returned object.

[01:11] We can run our test one more time and we should see that it passes. We've stored all headings as a data attribute on our virtual file. Altogether, we have acquired unist-util-visit, added a default headings value, visited every heading node, recorded the depth, aggregated the text, and then pushed that to our file.

[01:29] In our tests, you retrieved the headings data from our virtual file, then asserted against the headings that we expected.