Gatsby.js Remark Color Highlight

A plugin which highlights hex code colors on your Gatsby.js site.

Challenge

I was writing an article with many hex code colors inside, and something was off. As a programmer and therefore spending mass time in coding editors, I realized that my site didn't highlight color codes in their respective colors, as my IDE does.

So #FFBE0B would be a meaningless string (could you imagine the color, any color, if it was standard black text on a white background?), without any information what it means. Color highlighting is a beneficial feature, because it gives an immediate and precise understanding of an artificial token, that you can't possibly comprehend.

After finding that there is no color highlighting plugin for Gatsby.js, which this site is running on, I started coding.

Solution and Development

The plugin itself is not the only product that resulted from my findings. As this was project was an opportunity to learn something new, I also documented my learning path as a tutorial on developing Gatsby plugins.

Technically speaking, the plugin traverses through the Abstract Syntax Tree (AST), which is the data tree being created by Remark from Markdown, and wraps all occurrences of hex codes in a wrapper element.

It also considers the special case of HTML nodes, which it then creates a virtual DOM from so to speak, and again traverses its nodes to wrap all hex codes outside of XML tags (<tag></tag>) with a custom element. This is useful, if you want to transform hex codes in code snippets, e.g.:

body {
  margin: 25px 50px;
  background: #53777a;
  font-size: 0.975rem;
  color: #c02942;
}

Benefits

This project turned out to be beneficial for multiple parties. For instance, I learned how to write a Gatsby.js transformer plugin and shared my insights with readers of my blog. I also made the plugin publically available, so next time someone looks for a color highlighting plugin in the plugin directory, he will discover and - hopefully - use gatsby-remark-color-highlight.

Star