As with any tool that makes your life easier, The Law of Leaky Abstractions means there will always be gotchas!
In Svelte if all you want to do is show some JavaScript to your visitor:
<div>
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: user.id,
action: 'add-product'
})
})
</div>
You'll be in for a nasty surprise:
Module build failed (from ./node_modules/svelte-loader/index.js):
Error: ParseError: Expected } (5:10)
3: <div>
4: fetch(url, {
5: method: 'POST',
^
6: headers: {
7: 'Content-Type': 'application/json'
I think what's happening is that the otherwise useful expression syntax kicks in when it sees the {
and tries to read an expression from it. It's not very intelligent apparently and then just crashes when it sees a token that should not be in an expression.
Solution
Make the piece of code a Javascript string:
<div>
{`fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: user.id,
action: 'add-product'
})
})`}
</div>
Easy fix, yet not documented.