Alpine.js
Alpine is available everywhere as soon as you use it.
Alpine.js is auto-imported. Use Alpine in any script and the import is added for you; the runtime is split into its own alpine.runtime chunk. If you never use it, it's not in your bundle.
Dark mode is off.
Register stores, then start
Alpine is not started for you. Register stores, data and plugins first, then call Alpine.start():
/**
* Global entrypoint. `Alpine` is auto-imported, `Drupal` is a global.
*/
Alpine.store('darkMode', {
on: false,
toggle() {
this.on = !this.on
},
})
Alpine.start()
export {}
Use it in Twig as usual:
<div x-data class="rounded-lg p-6 transition-colors" :class="$store.darkMode.on ? 'bg-slate-900 text-white' : 'bg-slate-100'">
<p class="mb-4">Dark mode is <strong x-text="$store.darkMode.on ? 'on' : 'off'">off</strong>.</p>
<button type="button" class="cursor-pointer rounded-md bg-indigo-600 px-4 py-2 font-semibold text-white" @click="$store.darkMode.toggle()">Toggle dark mode</button>
</div>