CSS Parser in JavaScript?
Let me tell you a real-life story.
I work for a company which develops and sells Business Intelligence software. So the product is basically an SPA and we use a 3rd party library for the UI of our product. Last week, my boss walked up to my desk and told me that the UI Library just released an update and it’s my job to update our product as well. Not gonna lie, but I was pretty scared at first because it could have a major impact on our product. But as I dove deep into this task it seemed pretty easy. But little did I know what lay ahead. One fine morning while having coffee with my colleagues, my boss messaged me which had those dreadful words. “DID YOU UPDATE THE CSS FILES?”.
That was the day I started hating my job. My office routine was to open up the new and old CSS files [ we had modified the libraries CSS files to our liking]. Read through each one of them, look for differences and change the new CSS file so that it doesn’t change the color schema and the overall spacing and layout of our product. After 2–3 days of torture, I finally broke. But just as I was about to give up, JS God spoke and a ray of hope penetrated through clouds of sorrow and frustration.
I had written Node apps in my college days. An idea of writing a CSS Parser in node dawned upon me. So I opened up my then favorite text editor Atom, (now I am a VSCode guy) and with full enthusiasm started writing code. It took me a few hours to complete a basic parser and then a few more to make it handle special cases. I was pretty happy and proud with my work and guess what, I was able to finish the CSS file updations in a few hours.
The parser I wrote, outputted a JS object with selectors as key and value as an array of styles. With this, I was able to see which selectors were removed, which were newly added. Comparison between the old and new CSS files became a lot easier.
After coming home, I wrote one with a few modifications. I have made a GitHub repo for it which you can clone and use if you are in a situation like mine. It’s pretty basic, it still can’t handle a lot of cases but I am actively working on it and will push updates soon!
Thanks for reading and have a nice day!