I suggest telling us what compiler you are using as well. Vite or mix
Jan 9, 2023
3
Level 19
Dynamically register Alpine components
Hello,
I'm trying to dynamically load our Alpine.data components but I just can't get it to work despite trying a variety of things (I think it may be because import() returns a promise):
// typical import process
import component from './alpine/components/<component>.js';
Alpine.data('<component>', component);
// desired abstraction
const alpineComponents = require.context('./', true, /alpine\/.+\.js$/i, 'lazy').keys();
alpineComponents.forEach(component => {
Alpine.data(
_.camelCase(component.split('/').pop().split('.')[0]),
() => (import(`${component}`)),
// also tried
// async () => (await import(`${component}`)),
)
});
For reference, we are able to dynamically register our Vue components as follows:
const files = require.context('./', true, /\.vue$/i, 'lazy').keys();
files.forEach(file => {
Vue.component(
_.kebabCase(file.split('/').pop().split('.')[0]),
() => ({
component: import(`${file}`),
})
)
});
Edit: we're using Mix
Any thoughts? Thanks!
Please or to participate in this conversation.