DEV Community

Martin Betz
Martin Betz

Posted on • Originally published at martinbetz.eu on

6 2

How to use AlpineJS with Laravel Mix

This is another thing I do over and over and tend to forget how to properly do it: How can I use AlpineJS with Laravel Mix?

AlpineJS is a great lightweight library to sprinkle some interactivity into your website. I struggled a lot in the past with the question: "Do I really need to learn VueJS to get a simple dropdown account menu?" With AlpineJS, this is super simple to do.

If you want to use AlpineJS within your Laravel app, you can of course simply use the CDN version (<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.3.5/dist/alpine.min.js" defer></script>), but when I use other scripts as well, I prefer to have it bundled to one file to reduce requests.

Here's how to use AlpineJS with Laravel Mix:

  • npm install alpinejs
  • (in resources/js/app.js) Add the line import 'alpinejs';
  • (in webpack.mix.js) Make sure mix.js('resources/js/app.js', 'public/js') is there
  • npm run dev (or production or watch instead of dev)
  • (in the Blade file where you want to use Alpine) Insert <script src="{{ asset('js/app.js') }}" defer></script> in the <head> section
  • Use Alpine as described in the docs, such as the following account dropdown
<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul
        x-show="open"
        @click.away="open = false"
    >
        Dropdown Body
    </ul>
</div>

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (6)

Collapse
 
dendihandian profile image
Dendi Handian

anyone know how to add alpine persist plugin in laravel mix? ref: alpinejs.dev/plugins/persist

I'm having this error: Alpine Error: "ReferenceError: $persist is not defined"

Collapse
 
maximusblade profile image
Peter Sserwanga

@dendibaev did you ever get this fixed? how did you resolve?

Collapse
 
dendihandian profile image
Dendi Handian • Edited

I'm not sure but you can look at this file in my project github.com/dendihandian/grafify/bl...

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
dendihandian profile image
Dendi Handian

if you use Laravel Mix and build it with production mode, it less than 79Kb in size.

Collapse
 
flads profile image
Fábio Souza

Thank's, straight to the point!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay