laramatic.com

Alpinejs Laravel Mix CDN Tutorial

In this post Alpinejs Laravel Mix CDN Tutorial we have explained how we can install and use it. Before getting into we need to understand alpine basics with examples to make it more useful for you.

What is Alpine JS?

Alpine js is the newest JavaScript framework to create amazing front-ends for your projects. It can be used like Vue.js and React.js for its declarative and reactive nature. One important difference between Alpine Js and React/Vue is, Alpine JS does not require to run npm and compile scripts. Alpine JS can be configured with webpack exclusively on a 7.37kb CDN hosted file.  Just like using Tailwind for JavaScript, Alpine.js lets devs keep DOM and sprinkle as they want. 

Alpine.js uses Vue.js and Angular.js syntax which you will find very easy to use if you already have used Vue.js or Angular before. Even if you are new, you can still use it for your projects. It’s comparatively a new framework that will help you create amazing front ends for your projects. 

In this post we will explain how to install and use Alpine.js in Laravel 9. We will use two methods for this:

  • Using Alpine with Laravel Mix
  • Using Alpine.js with CDN

Using Alpine JS with Laravel Mix

To use alpine with Laravel Mix type this npm command in your terminal: 

npm install alpinejs

Next we have to import alpinejs in resources/js/app.jsfile

import 'alpinejs';

Now we are are able to run dev command to start

npm run dev

Once done with these steps now we are using app.jsfile which is required for blade file

<script src="{{ mix('js/app.js') }}" defer></script>
<div x-data="{ show: false }">
<button @click="show = !show">Show</button>
<h1 x-show="show">Hello Alpine.js</h1>
</div>

This is how we will use Laravel Mix alpine js and make our frontends high end.

Using Alpine JS with CDN

We will use Content Delivery Network file in this example to use alpine+CDN.  We can use Alpine.js using blade file. See example here:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>How to use Alpine.js with Laravel - LaraMatic</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.3.0/alpine-ie11.min.js" integrity="sha512-Atu8sttM7mNNMon28+GHxLdz4Xo2APm1WVHwiLW9gW4bmHpHc/E2IbXrj98SmefTmbqbUTOztKl5PDPiu0LD/A==" crossorigin="anonymous"></script>

</head>

<body>

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

        <button @click="show = !show">Show</button>

        <h1 x-show="show">Hello Alpine.js</h1>

    </div>

</body>

</html>

This is how we can install alpine on Laravel Mix and CDN and use it to create amazing web and mobile app front ends. If you have any queries regarding alpine js.