What is Alpine.js? How to install it and get started

Video thumbnail

Alpine.js is a lightweight and easy-to-use JavaScript library employed to add interactivity and functionality to web pages; its purpose is to present a minimalist alternative to more complex frameworks like Vue.js or React.

Alpine.js uses HTML attributes to add functionality to the page elements. It allows for DOM manipulation, conditional actions, event handling, and interactions in a simple and declarative way, without the need to write a lot of JavaScript code; all the logic can be defined at the attribute level or in a separate script block.

Some notable features of Alpine.js are:

  • Intuitive Syntax: Alpine.js uses a clear and easy-to-understand syntax, therefore, its learning curve is quite low.
  • Declarative Interactivity: It allows adding interactivity to HTML elements by adding special attributes like x-data, x-show, x-bind, among others.
  • DOM Manipulation: Alpine.js allows for simple DOM manipulation using attributes.
  • Events and Actions: It allows handling events like clicks, state changes, and key presses, and performing corresponding actions using directives like x-on and x-bind.
  • Size and Performance: Alpine.js is extremely lightweight, with a very small file size. This makes it ideal for small projects or for those looking for a simple solution without adding much complexity or overhead to the website.

Introduction to Alpine.js: Lightweight Reactivity

We are going to begin this introduction to Alpine.js. You can take this section, if you'll excuse the redundancy, as an introduction to the framework itself. Although this explanation is initially part of the Laravel Livewire course, it will be independent.

We will create projects from scratch working directly with Alpine and, later, in another section, we will link it with Livewire (which is the reason I am doing this introduction). Nonetheless, you can view this content regardless of whether you are interested in learning Laravel Livewire or not.

Alpine.js: The Lighter Vue

With that clarified, I wanted to talk a little about the framework. If you have already worked with Livewire, it should not be a big surprise, but I consider it necessary to make a formal introduction.

Alpine.js is another JavaScript framework, an important keyword, since nowadays there are many JavaScript frameworks with different purposes. This is one more; ultimately, you can see it as a kind of Vue, but lighter and simpler to understand.

I mention Vue because, in my opinion, frameworks like Angular and React are always considered a bit more complex.

Alpine's purpose is to handle simple operations. It is ideal when you don't need the complexity of Vue, but simply want to make small adaptations or add minimal reactivity.

⚙️ Structure and Reactivity in HTML

Alpine has a different, more modular structure. You don't have to create .vue files or anything like that, but you can create your "pseudo-components", so to speak, directly from the same HTML.

an Alpine component looks like this, always accompanied by directives starting with x-:

<div x-data="{ header: false }"></div>

The x-data directive is the key: it associates what is a component itself. As with Tailwind (although it is a different philosophy), we set the JavaScript directly in the HTML. We can create a separate script block if you want to do something more complex, as it also allows that.

In a nutshell, and comparing it again with frameworks like Vue, what Alpine allows us to do is add that layer of reactivity to our HTML page. When we change a property (for example, header), the DOM is automatically updated based on directives that we will learn about later (x-show, x-if, etc.).

Events and Modal Example

We also have events so the user can interact with our page. A good example of this is the creation of a modal or confirmation dialog.

<html>
   <body>
       <div x-data="{ open: false }">
           Open a modal
           </div>
       <div x-data="{ fieldText: 'Pon tu nombre' }">
           Handle a form
       </div>
   </body>
</html>

In the example above, open: false is our data. The idea is that if open is true, a conditional will open the modal, and if it is false, it will keep it closed or hidden.

️ Key Alpine.js Directives

Here the directives are the secret to reactivity. Of course, we also have events (x-on:click, x-on:keyup, etc.).

Regarding attributes, x-data is fundamental, as it indicates that it is a component and allows us to define our variables. Just like in Vue, we have:

  • x-show: To show or hide an element based on a boolean condition. It hides the div (keeping it in the DOM with display: none).
  • x-if: Similar to v-if in Vue (it removes the element completely from the DOM).

Alpine's Presentation Card

This is the official page (simply search "Alpine.js"). Here you can see the component's presentation. Look at the following example:

<div x-data="{ open: false }">
   <button x-on:click="open = !open">Click me</button>
   <div x-show="open">
       Hidden by default
   </div>
</div>

Here we have x-data with open defined as false. If the user clicks (x-on:click event), the open property changes to its opposite state. The div with x-show="open" will be shown when clicked. Unfortunately, we cannot execute it here, but this is its presentation card.

Alpine is an extremely simple and straightforward framework. The official page itself already defines its main attributes, properties, and methods, since by knowing these, you would know the most important part of Alpine, which is what we will cover in this course.

Installation

The next point is how we can install it. We have, just like with Vue, the option of:

  • CDN: This would be the option we will initially use for testing and the "Hello World".
  • Node/NPM: This is the ideal option for a real project.

You can go to the "Installation" section of the official documentation, where you will see the CDN method and the NPM method (which is initialized using import Alpine from 'alpinejs').

That was the introduction I wanted to give you: talking about the technology, what it offers, how it is structured, and how we can install it. Without further ado, let's go to the next lesson!

To be able to use Alpine JS, we can do it via Node:

$ npm i alpinejs

Or via CDN:

<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

The CDN will be the way used in this book as it is the simplest and, therefore, the most recommended way to start.

An Alpine application consists of two parts:

  1. The declaration of the data, using the attribute x-data.
  2. The functional part, which is using the logic you implement using Alpine's features.

Modularizing into Components

As I mentioned, the main feature of Alpine.js is that it allows you to create reactive micro-components directly in the HTML using the x-data directive. Here, we place the data and logic inline.

However, when the amount of JavaScript grows significantly, injecting everything into the same place (the x-data attribute) makes reading and maintenance difficult, leading to the dreaded "spaghetti code."

Therefore, if necessary, we can also create a separate JavaScript block to define the component's logic, somewhat replicating the scheme used in frameworks like Vue.

Creating External Functions for x-data

To achieve modularization, we simply create a classic JavaScript function that returns the object Alpine expects.

1. Function Definition

The function must return an object containing both the variables (the data) and the functions (the logic) that the component will use.

<script>
 function miComponenteData(){
   return {
     // Aquí se definen las variables reactivas (ej: 'todos', 'isOpen')
     // Aquí se definen las funciones que el componente invocará (@click="miFuncion")
     todos: [],
     incrementar: (value) => value + 1 
  }
}
</script>

2. Using the Function in x-data

Instead of placing the JSON object directly into the x-data attribute, we simply call the function. Alpine will take the returned object and assign it as the reactive data source for that div.

<div x-data="miComponenteData()">
   <template x-for="t in todos">
       <p x-text="t.task"></p>
   </template>
</div>

This way, in case the inline logic is insufficient or generates complex code, you can use this syntax to modularize your Alpine.js components, keeping the JavaScript in a clean script block.

The next step is to learn the x-bind of Attributes in Alpine.js of classes and styles

I agree to receive announcements of interest about this Blog.

We can use Alpine.js via Node or the CDN; in this article, we'll see how to install it. We'll talk a little about the framework and introduce the "Hello World" Alpine example, which will showcase its reactivity and component-based approach.

| 👤 Andrés Cruz

🇪🇸 En español