Initially, my script was:
The theme switcher function was within
And in my template, I initialized the theme switcher like this:
js.Build and loaded into the page:
Nothing too complicated, I thought, but still, on the console, I could see that while Alpine.js was properly initialized, the
themeSwitcher function was not being recognized or found.
It turned out ESBuild was excluding the
themeSwitcher function from the final build. I suspect it’s because the function wasn’t explicitly “used” elsewhere in the script, although it was clearly utilized in the theme.
After several trials (including an unsuccessful attempt to directly call
window object, similar to how I did with Alpine:
However, a minor issue arose with this change: Alpine.js generated a warning about being loaded before the
<body> was fully available. To address this, and to ensure proper script loading order, I modified the
Alpine.start() call to be done on
With this adjustment, everything fell into place smoothly. Feel free to maniacally toggle the theme switcher in the top right corner of this page to see the result.
This post is part of #100DaysToOffload 48 posts since Dec 04, 2022 — 85 total posts