I try to implement Alpine JS within a existing page.
For that, I’m using the CDN version of Alpine, which I’m loading within my :
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
Now I’m trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:
Alpine.magic('post', function () {
return function (url, data = {}) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(data)
});
}
});
Within my content I tried this:
<div x-data>
<h1>Alpine Test</h1>
<button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>
By clicking the button, this error occurs:
Uncaught ReferenceError: $post is not defined
I’ve also tried it with window.Alpine, without success.
How can I add magic properties and stuff like that without using modules?