Write Our First AlpineJS Program
Learn to write our first program in AlpineJS.
Set up AlpineJS
Like many JavaScript libraries and frameworks, we can add AlpineJS to a project in two ways:
- We can include it in the
<script>
tag. - We can install it through
npm
and import it as a module.
Both approaches work well with AlpineJS. It’s up to the developer to choose the approach they think is best for the project. The main advantage of the first approach is that we don’t have to do any extra setup. This is because AlpineJS will be available in our project.
Include AlpineJS in a <script>
tag
This approach is as simple as adding a <script>
tag to our web page:
<html><head><!-- Other tags --><!-- Add this to your web page --><script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script></head><!-- Body of your webpage --></html>
Note: We must not leave out the
defer
attribute in line 6. It ensures AlpineJS initializes beforeDOMContentLoaded
fires.
We can pull the latest version (or any other version) of AlpineJS to our project with this approach. In fact, we can see in the code above that we’re pulling the latest version of AlpineJS— version 3, in this case.
Hardcoding version numbers help prevent stability issues in production environments. Now that we’ve pinned the project to the stable version (v.3), we don’t have to worry about breaking changes in newer versions. Also, notice that this approach uses a
Use AlpineJS through npm
We can also install AlpineJS through npm
as a module. Then, we can import it into our project bundle to start using it. To install via npm
, we run this command from the terminal:
npm install alpinejs
It installs the latest version of AlpineJS in our project. After a successful install, we can import and setup AlpineJS like so:
import Alpine from 'alpinejs'window.Alpine = AlpineAlpine.start()
Let’s look at the code snippet above:
- We import AlpineJS to use in the bundle.
window.Alpine = Alpine
makes AlpineJS available in the globalwindow
scope. This makes it possible to play around with AlpineJS in our browser’s development(dev) tools.- The last line initializes AlpineJS. This means we can now use AlpineJS on our web pages.
Write our first AlpineJS program
To test our AlpineJS setup, we’ll create a simple program in AlpineJS. This is going to be an AlpineJS version of the famous “Hello World” program: “Hello Alpine.” We can achieve that with the following piece of code:
Press the “Run” button to see it in action. We can change the title
inside the x-data
directive to a different text, such as “Hello World,” and it’ll change the result.