I have a Alpine JS template that i want to reference x-data
from an array. I currently have that declared at the bottom of my HTML file in a <script>
tag, and i would like to move it in an external file. If I create the file and link it with <script src='path/to/file.js'>
my component stops working.
Example that works:
<div x-data="{items}">
<template x-for="(item, index) in items" :key="index">
<a :href="item.link" x-text="item.text"></a>
</template>
</div>
<script>
const items = [
{ link: 'foo.com', text: 'foo' },
{ link: 'bar.com', text: 'bar' },
]
</script>
Example that doesn't work, where external.js
has the same variable assignment
<div x-data="{items}">
<template x-for="(item, index) in items" :key="index">
<a :href="item.link" x-text="item.text"></a>
</template>
</div>
<script src="external.js"></script>
And the contents of external.js file:
import 'alpinejs'
window.onload = () => {
console.log('loaded') // This logs in the console
var items = [
{ link: 'foo.com', text: 'foo' },
{ link: 'bar.com', text: 'bar' },
]
}
I'm not sure what i'm doing wrong, help :(