Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Arifursdev/d54202603bd4aa2cd33e204452b095bb to your computer and use it in GitHub Desktop.
Save Arifursdev/d54202603bd4aa2cd33e204452b095bb to your computer and use it in GitHub Desktop.

See: alpinejs/alpine#3016

I have found the bset approach to be this:

Install Alpine.js from npm and bundle it with your js file (documentation). Don't assign it to window:

import Alpine from "alpinejs";
// Assign a custom prefix:
Alpine.prefix("xyz-");
// Don't assign Alpine to the window (keep it private):
// window.Alpine = Alpine;
Alpine.start();

document.addEventListener('alpine:init', function(){
    
	Alpine.data('custom_wp_plugin_xyz', function(){
        return {
            init(){
                console.log('init');
            }
        }
    });

});

Use a different prefix for each of your packages Keep in mind that the custom prefix will disable the @ shorthand for x-on:

<!-- will not work because of `@click` -->
<div xyz-data="{ show: false }" :class="{'is-shown': show}">
    <span xyz-show="show">👀</span>
    <button @click="show = true">Show!</button>
</div>
<!-- will work: -->
<div xyz-data="{ show: false }" :class="{'is-shown': show}">
    <span xyz-show="show">👀</span>
    <button xyz-on:click="show = true">Show!</button>
</div>

In my tests, the : shorthand kept working even with the custom prefix. To be on the save side, I would recommend to also not use that. So :class would become xyz-bind:class

So far I could not observe any conflicts between the two instances if following this approach. The only downside is that you won't be able to use the Alpine global directly in your HTML, but since I'm using re-usable x-data everywhere, this limitation doesn't impact me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment