Installing Alpine
Alpine is added in one of two ways: with a <script> tag pointing to a CDN — a server that hosts ready-made library files — or as an npm package in a project with a bundler. The first way is simpler, the second fits better when the site already has a JavaScript build.
From a CDN
Create a project folder with an index.html file in it:
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>To-do list</title>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body>
<h1 x-data="{ title: 'My tasks' }" x-text="title"></h1>
</body>
</html>Open the file in a browser — the heading "My tasks" appears. Alpine output it from the component's data.
The defer attribute is required: it delays the script until the browser has read all the HTML. Then Alpine sees every element with x-data.
The alpinejs@3.x.x part loads the latest release of version 3. On a production site, pin an exact version such as alpinejs@3.14.9, so a library update does not change the page's behavior unexpectedly.
From npm
If the project is built with Vite, create it and install the package:
npm create vite@latest todo -- --template vanilla
cd todo
npm install alpinejsThe vanilla template creates index.html in the root and a src/main.js file. Replace the contents of src/main.js:
// src/main.js
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();The import loads the library, and Alpine.start() starts it: Alpine walks the page and brings the directives to life. Assigning window.Alpine is optional, but it lets you reach Alpine from the browser console.
Add the same heading to the <body> of index.html and start the dev server:
npm run devThe site opens at http://localhost:5173.
Which to choose
| Way | When it fits |
|---|---|
| CDN | Static pages, backend templates, quick experiments |
| npm | The project already uses Vite or another bundler, you need plugins and your own code in modules |
All examples in this course use the CDN, so they run right on the lesson page.
Common mistake
Calling Alpine.start() twice, or loading Alpine both from the CDN and from npm. Then every component starts twice: handlers fire twice and the console shows warnings. Keep one way of loading and one Alpine.start() call.