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
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
: definecount
stateonClick()
:- Define
onClick
event handler to increasecount
state - Use
this
to access state like Vue
- Define
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 tox-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 incounter.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