In this post, you'll learn how to set up Alpine Js version 3 for your Laravel 8 projects. The steps are very straight forwards so let's get started.
There are 2 ways to include Alpine Js into your project:
There are 2 ways to include Alpine Js into your project:
- Using the CDN
- Install locally using yarn or npm
1 - Using the CDN
When using the CDN you can directly just define a "script" tag and put in the CDN as the src and you can automatically write Alpine Js in your Laravel blade views.
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
The full code example is like below.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello World</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script> </head> <body> <div x-data="{ name: 'postsrc' }"> <span x-text="name"></span> </div> </body> </html>
2 - Install Locally Using yarn or npm
To install Alpine Js locally you can use "yarn" or "npm" and with Laravel, you can make use of the Laravel Mix build tool and get the best out of it.
yarn add alpinejs // for npm npm install alpinejs
Now define a new config for the webpack.mix.js to specify the file to be processed.
// webpack.mix.js mix.js('resources/js/alpine.js', 'public/js');
Inside the "resources/js/alpine.js" file you can import alpine as a module. Do note that in order to initialize Alpine Js version 3 you have to call the "Alpine.start()".
// resources/js/alpine.js import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start();
Now you can "run watch" or compile it to production with "yarn prod".
yarn watch yarn prod
Register Alpine Js Components
Once you have defined your custom Alpine Js component, it's also recommended that you register your components in the following way. This will allow for better code abstraction and reduce your main script in general.
// resources/js/alpine.js import Alpine from 'alpinejs'; import navbar from './components/navbar'; import sidebar from './components/sidebar'; Alpine.data('navbar', navbar); Alpine.data('sidebar', sidebar); Alpine.start();
The content of the component should export the default function like below.
// resources/js/components/navbar.js export default () => ({ open: false, toggle() { this.open = ! this.open } })
Finally, don't forget to reference the javascript in your blade views.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello World</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <script src="{{ asset('js/alpine.js') }}"></script> </body> </html>
By now you should be able to set up Alpine JS for your Laravel 8 project. If you find this tutorial to be helpful do share it with your friends and happy coding 🍻
Leave a reply