Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cwhite's avatar
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!

0 likes
3 replies
Sinnbeck's avatar

I suggest telling us what compiler you are using as well. Vite or mix

cwhite's avatar
Level 19

@Sinnbeck, ah that would make a difference I suppose. We're still using Mix.

cwhite's avatar
Level 19

Update:

So I read that an Array's forEach method is not very async friendly, so I tried to use a regular for of but it's still not working:

const alpineComponents = require.context('./', true, /alpine\/.+\.js$/i, 'lazy').keys();

for (const file of alpineComponents) {
    (async () => {
        await import(`${file}`).then(module => {
            Alpine.data(
                _.camelCase(file.split('/').pop().split('.')[0]),
                module.default,
            );
        });
    })();
}

If I assign window.module = module.default and inspect it in the browser later I see the same module object as doing a import module from <js_file>, but the Alpine component still doesn't load.

Please or to participate in this conversation.