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>
<!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
// webpack.mix.js mix.js('resources/js/alpine.js', 'public/js');
// resources/js/alpine.js import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start();
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();
// resources/js/components/navbar.js export default () => ({ open: false, toggle() { this.open = ! this.open } })
<!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>