Search code examples
javascriptmodulealpine.js

Importing AlpineJS via (inline) script module


Since I wanted to add some modules to Alpine JS, I tried to load Alpine via script module as descriped in the documentation. However, somehow I must have misunderstood something or made a mistake, since it does not work.

Notes:

  1. I downloaded the script and saved it accordingly in modules/alpine.js
  2. I use Visual Studio Code and run the preview using the Live Preview extension from Microsoft
  3. With the import path used below I get this 404 error: GET http://127.0.0.1:3000/modules/alpine net::ERR_ABORTED 404 (Not Found)
  4. When I change the import path of AlpineJS to ./modules/alpine.js I get the the following error: Uncaught SyntaxError: The requested module './modules/alpine.js' does not provide an export named 'default'

<!-- <script src="//unpkg.com/alpinejs" defer></script> This would work -->
<script type="module"><!-- This does NOT work -->
    import Alpine from './modules/alpine';
    Alpine.start();
</script>

<div x-data="{ test: 'hello world' }">
    <span x-text="test"></span>
</div>


Solution

  • Since you want to import Alpine.js as a module, you have to import from the module build, not from the CDN build.

    Install Alpine.js with a package manager:

    npm install alpinejs
    

    Then you can import Alpine.js as a module from ./node_modules:

    <script type="module">
        import Alpine from './node_modules/alpinejs/dist/module.esm'
        Alpine.start()
    </script>
    

    If you wish you can also copy module.esm to a different directory and delete node_modules.