How to Modify Nodes in an Abstract Syntax Tree | CSS-Tricks
This code takes advantage of Node’s built-in fs module, which allows us to access and manipulate the filesystem. For more information on how this works, check out the official docs.
Thanks to the hard work of the open-source community, remark does all the hard work of turning Markdown into HTML for us. (See the diff)
Transforming an AST is usually done using the visitor pattern.
The important thing to know is that the majority of resources on AST work will talk about “visiting nodes,” which roughly translates to “find part of the AST so we can do stuff with it.” The way this works practice is that we write a function that will be applied to AST nodes matching our criteria.
To wrap our img element with a figure element, we need to write a plugin. In unified, plugins are added with the use() method, which accepts the plugin as a first argument and any options as a second argument:
The plugin code is a function (called an “attacher” in unified jargon) that receives option. These options are used to create a new function (called a “transformer”) that receives the AST and does work to, er, transform it. For more details on plugins, check out the plugin overview in the unified docs.