How to Fix 'Alpine Expression Error'
This is the first site where I’ve used Alpine.js. I initially ran into some errors with undefined things, even though my code matched the docs.
Example Code and Error Message
Here’s some example code that updates the date in the footer with the current year:
<footer class="page-footer" x-data="{ d: new Date().getFullYear() }">
<p>© <span x-text="d">2022</span></p>
</footer>
My code matches the example from the docs, but it was giving me errors like this:
Alpine Expression Error: func(...).catch is not a function
Expression: "{ d: new Date().getFullYear() }"
<footer class="page-footer" x-data="{ d: new Date().getFullYear() }">
Alpine Expression Error: d is not defined
Expression: "d"
<span x-text="d">
The Solution: ES2017
It turns out that Alpine.js needs a target of ES2017 or higher to work. (Explained here, here, and here.)
In my case, Parcel was using this line from package.json when transpiling the TypeScript to JavaScript:
"browserslist": [
"defaults"
],
which is equivalent to "> 0.5%, last 2 versions, Firefox ESR, not dead".
Removing the “browserslist” entry in package.json fixed it. If you’re using another build tool (tsc, babel, etc.), change the build target to “ES2017” or later, and that should fix it.
The New Problem
One problem with ES2017 is that it won’t work on older browsers like Opera Mini or older versions of Safari, including old iPads, but that’s the only way to get past the Alpine.js error at the moment.
(Update: This site doesn’t use Alpine.js any more, because I migrated it to Next.js.)