Starting with Alpine.js
// updated 2025-09-18 11:20
Alpine.js tries to bring web development back to the days before complex build systems and esoteric DevOps, but with a cleaner approach, by:
- embedding a "framework" JavaScript file within a
<script>
tag in an HTML file - containing JavaScript within special HTML attributes called directives which carry the prefix
x-
- (side note: this has nothing to do with that social network!)
Setup
We begin with a plain index.html file (and nothing more):
1<html>
2
3 <head>
4
5 <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.15.0/dist/cdn.min.js"></script>
6
7 </head>
8
9 <body>
10
11 </body>
12
13</html>
With the defer keyword, Alpine.js will load parallel to the loading of the page but the script will only execute after the page has finished parsing!
Simplest counter app
To show how streamlined and minimalist Alpine code can get, let's have a look at the simplest counter app you'll see today:
Yup, in just four lines in the <body>
tag, we have the logic and the look of the counter app, ready to use and style further! From the code above, we can glean:
x-data
acts as a state variable, much like useState in React, declaring all the variables in a JSON formatx-on:event
takes on values with basic JavaScript logicx-text
uses the variables inx-data
Okay, this looks oversimplified ... counter apps don't need much but imagine the overhead necessary to build this in, say, React or Next.js, or even vanilla JS!
Adding multiple state variables
Let's add in a state variable just to see how far this goes:
So, x-data
can store multiple variables which we can use in events and labels!
Operations on variables
Further operations on state variables such as arithmetic:
Note that the labelling and the operations can occur within a single directive!
Exercise
Try building a counter with an additional button that decrements (decreases by 1) the value of the count!