點燈坊

失くすものさえない今が強くなるチャンスよ

Loading Alpine by ES Module

Sam Xiao's Avatar 2022-08-13

Alpine is traditionally loading by CDN, but we can also initialize Alpine by ES module.

Version

Alpine 3.8

ES Module

esmodule000

The classical counter is loading by ES module.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Alpine</title>
    <script type="module">
      import Alpine from "https://unpkg.com/alpinejs?module";

      Alpine.start();
    </script>
  </head>
  <body x-data="{ count: 0 }">
    <button @click="count++">+</button>
    <span x-text="count" />
  </body>
</html>

Line 7

<script type="module">
import Alpine from "https://unpkg.com/alpinejs?module";

Alpine.start();
</script>
  • Import Alpine by ES module
  • We have to use Alpine.start() to initialize Alpine

Line 13

<body x-data="{ count: 0 }">
  <button @click="count++">+</button>
  <span x-text="count"/>
</body>

Classical counter implemented by Alpine.

Conclusion

  • By using ES module to initialize Alpine, we have to use Alpine.start to initialize Alpine manually