DEV Community

Discussion on: Build modular app with Alpine.js

Collapse
 
marzelin profile image
Marc Ziel
<script defer type="module">
Enter fullscreen mode Exit fullscreen mode

Adding defer attribute to inlined scripts has no effect. It only works here because modules are deferred by default.

Why don't you just add alpine import to index.ts and do component initialization there? Using this loader here makes no sense to me.
If you don't want to repeat initialization in every index.ts, you can do this in an inlined module:

<script type="module">
    import alpinejs from 'https://cdn.skypack.dev/alpinejs';
    import * as comps from '/dist/demo/index.js';
    Object.keys(comps).forEach(comp => {
      let data = comps[comp]();
      alpinejs.data(comp, () => data);
    });
    alpinejs.start();
</script>
Enter fullscreen mode Exit fullscreen mode

Also, you're awaiting for alpine before starting components loading. You might start loading it in parallel and then continue component initialization when it's ready:

export async function loader(moduleURLs) {
    const alpineP = import('https://cdn.skypack.dev/alpinejs');
    const modules = await Promise.all(moduleURLs.map(async (modURL) => {
      const module = await import(modURL);
      const { default: alpinejs } = await alpineP;
      Object.keys(module).forEach(attr => {
        let data = module[attr]();
        alpinejs.data(attr, () => data);
      })
      return module;
    }));
    alpinejs.start();
    return modules;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
keuller profile image
Keuller Magalhães

Hey @marzelin thanks for your observations.

Collapse
 
mikaelalfort profile image
Mikael Alfort • Edited

How would you extend your code/solution to import modules when needed, e.g. on a click? I have seen lazy loaded import but how can I access alpinejs?

I think your second example code tries to do just that, but I get error in console:

loader.js:12 Uncaught (in promise) ReferenceError: alpinejs is not defined
at loader (loader.js:12:2)