Modules in the Browser and Yaks
Diving deep into the murky shallows of the web and shaving yaks
Building websites
So far every website I have ever built was either created using a JavaScript framework’s default tools, Jekyll, or plain HTML/CSS/JS.
I decided I wanted to learn to build websites using build tools that I configured myself. Vite has been the most popular as far as I know. So I went to their homepage. The helpful ‘Why Vite?’ link caught my attention. Navigating to the next page, I soon lost attention.
I had no idea what ‘modules’ were. And that is all that the page was talking about.
What are modules?
Is the question I embarked to answer. Of course by modules, I mean ESM–ECMAScript Modules.
MDN’s article on JavaScript Modules is where I begin my journey. To play around with the concepts I started building a website that was definitely not inspired by Svelte’s tutorial.
It was simple enough. A numeric counter that updates based on user input. The user is given two buttons: one to increment the counter and the other to decrement it.
But what’s the point of having modules if there’s only one thing done?
Observing the counter
aka yak-1
To keep experimenting with modules, I did add a few console.log()
statements because duh. But I also went a bit further and
decided to persist the counter between sessions.
Normally, I would use localStorage.setItem()
as part of the button’s
click event handler. This time I decided to try something different.
Hoping that doing this would not block the main thread, I used the
MutationObserver
API to watch the DOM change and store to localStorage when it does.
Might be better to use a promise or some mechanism to debounce. But those are things I thought of now; not when I was working on it.
A Spinner
aka yak-2
Because I was storing to localStorage, I had to read from localStorage on page loads. While the browser storage is fast, it is visible when the value changes at initial load.
So I wrote a spinner SVG. COMPLETELY BY HAND! Okay I mean manually.
I even added animation! TADA!
The inspiration was a recent episode of HTTP203 titled “Demystifying SVG Paths”
the episode worked! i wrote some SVG manually! 🐢
— Kevin Samuel (@kevinnlsamuel) July 26, 2022
then i forced the user to see it because i wanted to show off
I now know modules
aka finish shaving yak-0
I realised only while writing this post that my entire journey learning about modules was a yak shaving trip in itself.
I had started because I wanted to try out Vite…