-
Hi there! I have a scenario where I have to run multiple independent Alpine instances on one page (two custom plugins that are completely unrelated and could be installed together or alone). I'm using npm/webpack in both of these plugins. How can I prevent collisions with the two Alpine packages? This is the best I could come up with until now (simplified code): import Alpine from 'alpinejs'
import MyComponent from './components/alpine/MyComponent/MyComponent.js'
if( !window.Alpine ) window.Alpine = Alpine;
window.Alpine.data('MyComponent', options => MyComponent(options))
let alpineAlreadyStarted = false
document.addEventListener('alpine:init', e => alpineAlreadyStarted = true)
window.addEventListener('DOMContentLoaded', e => {
if( !alpineAlreadyStarted ) window.Alpine.start()
}) Basically, I am re-using the window global Maybe an alternative approach could be to use some unique prefix for each of my plugins like Does anyone have an idea how this could be solved in a cleaner way? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
@hirasso, i'm not here for the prefix feature, but to thank you for |
Beta Was this translation helpful? Give feedback.
-
I'd also be interested in the ability to customize the prefix! I'm using Alpine to manage interactivity on JamComments, and don't want to worry about potential conflicts w/ another version of the library loaded on the page. |
Beta Was this translation helpful? Give feedback.
-
I'd suggest finding a better way to deconflict. Otherwise you're just repeating the age of jQuery sites where every site has 16 version of jQuery loading. |
Beta Was this translation helpful? Give feedback.
-
I have found the best approach to be this:
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();
<!-- 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 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 |
Beta Was this translation helpful? Give feedback.
I have found the best approach to be this:
window
:@
shorthand forx-on
: