點燈坊

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

Building Modular App with Alpine

Sam Xiao's Avatar 2022-08-13

Alpine doesn’t support ES Module completely. But we can still build a modular app with Alpine by coding style.

Version

Alpine 3.9

Traditional Alpine

modular000

Classical counter implemented by Alpine.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="counter">
    <button @click="onClick">+</button>
    <span x-text="count" />
  </body>
  <script>
    let counter = {
      count: 0,
      onClick() {
        this.count++
      },
    }
  </script>
</html>

Line 9

<body x-data="counter">
  • Data is not defined in x-data
  • Bind an Object to x-data directive

Line 14

let counter = {
  count: 0,
  onClick() {
    this.count++;
  },
};

Create counter Object by JavaScript :

  • count : define count state
  • onClick() :
    • Define onClick event handler to increase count state
    • Use this to access state like Vue

Modular Alpine

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="counter">
    <button @click="onClick">+</button>
    <span x-text="count" />
  </body>
  <script src="counter.js"></script>
</html>

Line 9

<body x-data="counter">
  • Bind an counter Object to x-data directive

Line 13

<script src="counter.js"></script>
  • Import counter.js synchronously

counter.js

let counter = {
  count: 0,
  onClick() {
    this.count++;
  },
};
  • Define counter Object in counter.js

Conclusion

  • Since Alpine doesn’t fully support ES module, what we can do is using coding style to build modular app
  • Create only 1 Object in JavaScript file, and the Object name and file name are the same to make the code more maintainable