1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Store Heading Metadata in a Markdown Document with remark

    John OtanderJohn Otander
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    In our tests, you retrieved the headings data from our virtual file, then asserted against the headings that we expected.