Add a self hosted alpine.js file with Laravel

Laravel by default uses a CDN to load alpine.js. That can be a problem in regard of GDPR. To self host the alpine.js file, you have to install alpines:

npm i alpinejs

There is something special with alpine.js - it must not be loaded before LiveWire initializes. That’s why we put alpine.js in a separate file, so that we can add defer to the script tag. To do so, add a resources/js/alpine.js file with this content:

import 'alpinejs'

Next step is to add the alpine.js file to webpack.mix.js. To do that, you have to add this to the end of the file:

mix.js('resources/js/alpine.js', 'public/js')

Last step is to include the script in your templates <head> tag:

<script src="{{ asset('js/alpine.js') }}" defer></script>

When you now run npm run prod, an alpine.js file is created in your public folder and everything should work as expected.