AlpineJS – JavaScript solution in Hyvä Themes
We’ve already written about Hyvä Themes that is a new approach to the Magento 2 frontend. It was clear from the start that recreating M2 theme meant also cleaning up Magento 2 JavaScript. We needed modern, lighter and more consistent JavaScript code and it was high time to say goodbye to jQuery, KnockoutJS and RequireJS. And as Hyvä Themes is still simply a theme and not a SPA (Single Page App) solution for Magento, its creators haven’t decided on React or Angular and have chosen AlpineJS instead.
What is AlpineJS?
AlpineJS](https://github.com/alpinejs/alpine) is a JS library and “offers you the reactive and declarative nature of big frameworks like Vue or React at a much lower cost.” It can be an interesting choice if you don’t want or don’t need to build your app primarily on JS and instead, you just want to sprinkle some JS when needed. There is no build time, it is lightweight (26kb minified) and seems to be an interesting and modern replacement for jQuery. Taking it all under the consideration, it was a natural choice for Hyvä Themes.
x-on
x-on:click
@click
x-bind
x-bind:class
:class
x-show
x-html
x-model
x-if
x-for
x
v
$event
$refs
You can find full documentation here: https://github.com/alpinejs/alpine
Tailwind for JS?
Alpine’s creators state that it is like “Tailwind for JavaScript”. Hyvä Themes uses Tailwind for styling so pairing them up shows a consistent approach to creating code. But what does this “Tailwind for JS” mean? Well, AlpineJS is very HTML-centric. Not only because you don’t create separate JS files and you write your scripts inside HTML ones, but more importantly because you can actually achieve many things without even leaving your HTML code and opening the script tag. It makes Alpine similar to Tailwind since with Tailwind you can do quite a lot of styling from within your HTML and without manually adding a single CSS class. Let’s see a simple example of toggling content with AlpineJS:
You can see a live example here.
x-data
This won’t be enough for more complex situations, but you can go quite far with it. Or you can decide that you need a script tag after all:
initUserData()
submitData()
@submit.prevent
{{}}
x-text
You know how it is in JS world - new frameworks/libraries pop up constantly. Some of them stay with us for longer, some will quickly become forgotten. Alpine can find its niche though. It has already found quite a nice use in Hyvä Themes.
Would you like to innovate your ecommerce project with Hatimeria?
A mountain lover and code climber. She can reach any peak and conquer any coding challenge. Loves ramen, reading books and watching TV series. Wins every Hatimeria competition.
Read more Julia's articles