Svelte is a language(gist.github.com) |
Svelte is a language(gist.github.com) |
All Javascript frameworks may become implementations of SAT solvers, where rendering and state are scheduled constraints, i.e. tiny operating systems.
NPM uses CSS as a query language - https://news.ycombinator.com/item?id=33136843 - 9 months ago
Then apps may be instantiations of the framework.
No different from what most non-frontend developers want by the way.
Problem is; that is not yet possible at all, because ‘the spec’ is too vague and strictness generated from vagueness will either be just vagueness (cannot find any constraints to throw into a solver so just leave it) or too strict (where many cases simply are suddenly forbidden that were actually feasible cases by the author).
<button on:click={incrementCount}>
Specifically, what is on:click? It doesn’t look like JavaScript, and it doesn’t look like the DOM. It looks like a new language which is specific to Svelte.Or what about this… is this JavaScript?
$: doubled = count * 2;
Or… {#if user.loggedIn}
<button on:click={toggle}> Log out </button>
{/if}
Or… <button on:click|once={handleClick}> Click me </button>
I am willing to believe that all of that is ergonomic in some way, but it doesn’t appear to me at first blush as very JavaScript-y, or explicit. I see a lot of black box stuff controlled by a declarative API.it's not. it's html. incrementCount is a pointer to a javascript function.
> Or what about this… is this JavaScript? > $: doubled = count * 2;
Yes. $: is a javascript label. We use it to indicate that a function should be reactive - if the count variable changes, the right hand will be rerun and double updated.
> <button on:click|once={handleClick}> Click me </button>
html again. the |once is a modifier to click which detaches the handler after a single use. It's a directive in the html markup (still valid html) which the compiler picks up and converts into node.removeEventHandler.
I love svelte but I'm having a hard time getting the same development ergonomics out of svelte kit. It's probably just me.
This is funny because it's exactly the reason I prefer react
Two great things about this "thinking inside the box" approach are:
1. You're encouraged to use native APIs because they're highly unlikely to clash with the framework.
2. You can a legible stack trace. After all, the only thing the compiler does to your JavaScript is add some instrumentation here and there.
I've converted my company website to svelte-kit from first Angular, then Vue.
But for SPA it's bad. If you use oidc auth. There's only Auth.JS and it's a confidential client, for Svelte Kit.
If you're not using svelte-kit you can use vite to create a Svelte SPA. There you can use your PCKE client as usual and burden the load on the client.
I have yet to experiment with how well it works with a graphql client. Apollo has its own cache but I'm not sure there is a svelte version of it. There is for Vue. Does it even need one? The default is for React. Is Apollo even needed? Questions over questions.
Why Svelte? Performance. Performance matters, a lot.
Svelte being a "language". First time using a template system? I have to wonder.
This makes tooling complicated and a debugging that works out of the box for both server and client side is non existent even in SvelteKit 4.
When I'm picking up SvelteKit, it's only for its routing which isn't so great either with file based arrangements, things get out of and pretty fast.
My point is this is not a syntax decision that React made, but svelte's syntax was (as far as I can tell) a decision.
To be fair, Observables and especially Observable composition has a rough learning curve and many frameworks like Svelte intentionally prefer implict reactivity and avoiding things like explicit Observables because they are seen as too complex/"too hard" for the average developer.
(Then you get awful worst of both worlds frameworks like Angular that sort of rely on Observables but yet also don't trust teaching Observables and wind up with code that isn't properly Observable and so also has all the code for implicit reactivity and is full of nasty escape hatches that cause all sorts of composition problems and unnecessary side effects.)
Svelte I've never quite got the hang of to the point where I feel comfortable expressing an opinion about it (and I haven't spent enough time experimenting to claim my not having got the hang of it yet means anything either).
I don't think that's a good direction to go.
I was excited about svelte, but have found that coming back to my svelte project after a month or two of not using it was arduous because of all the myriad language level things. There are just too many little svelte specific things to keep track of in head.
In contrast coming back to a react/vue project is much easier for me, because even if I forget something at the end of the day any vue-directive or react hook is just another js/ts api I can easily lookup.
In particular, I find the DX that volar+vscode offer in a project with vue3, composition API & pug templates to be better than anything else I have seen in the FE ecosystem in last 5 years.
I also don't find the enhancements for local reactivity to be major value additions because most of the times my state resides in a shared store. I find the vue reactivity model to be simpler to deal with because I can create shared stores which can be (deep) mutated from any component and it all just works seamlessly.
Familiarity wise Angular has been probably the easiest to jump into and maintain long term, but it is a pain to work with due to the amount of ceremony involved to do even the simplest of things.
Svelte codebases due to the very nature of Svelte are simpler and very straightforward to get into, there are some svelte specific things but they aren't too many of them and are simpler to reason about when compared to codebases built on hooks, and even worse are hooks in combination with junior Devs. It is very very easy to write bad react code and you see this way way too often. Most react code out in the wild is badly written, you don't see problems because the browsers and modern computers are performant enough to hide them away but you do notice as the codebase grows and you realize it too late that the very foundation was wrong.
I don't mind Vue and just see svelte as a nicer DSL over it.
I'm currently finally doing a big React project, and boy, the complexity is spiraling a bit out of control. It's certainly not DRY.
If you have a minute, I'd love you to expand on that. I have some thoughts along those lines myself but I suspect you've spent more time with mobx than I have and would rather hear yours from cold.
(I also keep looking at mobx-state-tree and wondering if that would work for me, I'm not sure I know enough to judge what the trade-offs involved are particularly well)
The main issue is, that it becomes a nightmare to transmit and compose meta-information. An example would be the fetchStatus of ReactQuery [1].
I way too often end up in situations like this:
.map {
unwrapMetaData
...
rewrapMetaData
}
...
.map {
unwrapMetaData
...
rewrapMetaData
}
.switchMap {
// unwrap metadata and wrap it in an observable
combineLatest(...) // have fun juggling an array of nested monads :)
}
I wonder if it is possible to create a mixture between React hooks and async/await. Since you tend to work in one big scope, you could ignore the meta-info until you need it. async live function() {
const { value, meta } = observe getValue(...) // suspends when loading, throws on error
// work with values
const multipleValues = observe Observe.all(...map(i => ...))
// more work
// evaluateMetadata
}
[1]: https://tanstack.com/query/v4/docs/react/guides/queries#fetc...I’ve worked on very complex Rx code bases. I like Rx, but it gets it be a huge pain the debug when you have very complicated chains. I haven’t used hooks too much, but from what I’ve seen the default behavior is to “do the wrong thing” which makes them very annoying to work with. The implementation of hooks is also very hacky. Like you can’t create a hook inside an if statement. That’s crazy.
async *function someMapOperation() {
const { value, meta } = await getValue(…)
doSomething(meta)
yield value
for await (const { value, meta } of AsyncIterableX.from(mergeAll(…).pipe(takeUntil(…)))) {
doSomething(meta)
yield value
}
// …
}
(I've done similar things in C#, as well, with its Rx/Ix pair.)You are right, there are still good cases where being able to write the "state machine" of a complex flow as an async (generator) function makes it a lot easier to reason with. The nice thing is that Observables work well with AsyncIterables and a pipeline doesn't have to be just one or the other.
Last I checked (and things may have changed since) is that svelte didn't support transparent reactivity for deeply nested objects. So something like `$myStore.foo.bar = "baz"` wouldn't trigger a component update, you need to remember to use .set, .update etc. You could assign to local reactive variables but you couldn't assign to stores.
I am sure the library authors made these trade offs thoughtfully, I was just disagreeing with the blanket statement that Svelte is generally a major improvement over Vuejs.
Nothing preventing them from making an <If condition={…}>…<Else>… component
Take the ability to reference functions in HTML - this is simply not possible in normal HTML, where inline event handlers instead are passed Javascript expressions to evaluate. It's definitely a useful feature, but it's very clearly outside of the normal realm of HTML.
This goes further with Javascript: here the semantics differ considerably, with labels in normal Javascript doing nothing except when dealing with loops, and labels in Svelte are a form of reactivity. You've also got things like dollar signs interacting with stores, and other semantic differences.
As Rich Harris says, Svelte is a language.
100% valid HTML and within "the normal realm of HTML". The event is passed as a parameter to the function. Has been available since the introduction of JavaScript. Predates addEventListener(…) and its ilk by a few years.
Yes, "$:" as a labeled break exists outside JavaScript proper. That said, given the rare cases where anyone uses a labeled break and how unlikely that labeled break would be named "$", it seems a pretty safe extension to the language to allow such powerful behavior.
Both "$:" and "$store" are not magical; they are quite deterministic and serve to substantially reduce the total amount of boilerplate. Seems a fair tradeoff, but you are correct, it's a superset of the JavaScript language.
Now let's discuss the "naturalness" of useState, useMemo, and their ilk. I'll take Svelte's minimal "magic" over the verbose, repetitive, and error-prone library API logic, thank you very much.
Like I said, it's valid HTML, but it doesn't do what you're describing (and you can try it out fairly easily in your browser). The "onclick" handler executes the code string that it's given, working essentially the same way as `eval` or the `new Function("...")` syntax. It does not take a function pointer.
So in this case, the only thing it executes is a variable pointing to a function, which doesn't do anything because the function isn't being executed. You would need to add the function brackets to get any sort of effect.
This is the crux of the issue: Svelte is an additional language that happens to use the same syntax as HTML and JS, just with different (in some cases very different) meanings. You are not just writing "explicit Javascript code", you're writing Svelte code (which in most cases is probably very easy to pick up if you know Javascript, but it's still a different language).
Compare and contrast with, say, Typescript, which is syntactically different from Javascript, but semantically identical - just remove the types, and you have normal Javascript. (In fairness, with old decorators and enums, this isn't quite true, but it holds in general.)
To be clear, I don't think that's saying that one thing is better than the other, or that Svelte is bad because it's a new language or something. I think reactive primitives in Javascript are important, and adding them directly into the syntax of the language is a really clever way of solving a lot of problems in this space. I'm not sure if it's the solution I like the best (I've really enjoyed working with SolidJS signals recently, which provide some of the same ideas with a more typically Javascript-like API), but it's good to see experimentation here.
I think this is the crux of the gp's question. The browser doesn't support explicit behaviours for "on:click" or "|once" (the "$" label is a cool trick I'd forgive the gp for not recognising as native JS) - it may be "valid" HTML but it's not "just HTML" (nor just JS), it's a DSL.
Anyone who already knows HTML and native event handling could pick this up in less than 5 minutes. Good enough.
Centering JS has always been like putting the cart before the horse.
In practice what I've found is that HTML is fine/optimal for event-driven interactions layered onto entirely static content, but for inherently interactive UIs, what ends up happening is you get one of two systems:
1. If you start from a HTML-forward standpoint, you can go a certain distance separating your concerns entirely, but at scale the drawback is maintaining disparate references, negatively impacting code colocality: having to edit a reference in three separate files in a repo is incredibly bad for DX and readability. To overcome this, a common approach is to make the JS side generic by embedding DSL with dynamic functionality into your HTML: the worst of both worlds, creating both a Frankenstein HTML+weird-extras language and still needing to bundle JS with it.
2. If you're starting a greenfield project with the early intent of having a fully interactive UI, instead of growing into it, you can avoid the above mess and architect your project from the offset with good code colocality by embedding templates for highly dynamic/transient UI components into the imperative part of your application logic (i.e. the JS).
I have yet to find a greenfield React project with more than a few developers over a few years that didn't turn into a big ball of mud that only the original developers could understand (at best). State management alone on React is an utter, total, and indisputable shitshow. Codebases with a mixture of classes and functional Hooks are far from ideal for developer experience.
Svelte code by comparison is a breath of fresh air both to develop as well as maintain. Whether Svelte wins or something inspired by Svelte does not matter as much to me as something that takes away the inverted JSX model, the virtual DOM, and allows the use of vanilla libraries without React wrappers interfacing with other React wrappers.
Haven't looked at angular since 2015 to be honest, but it still seems like they do weird html stuff to me, such as:
<ul> <li *ngFor="let customer of customers">{{customer.name}}</li> </ul> or <label>Type something: <input #customerInput>{{customerInput.value}} </label>
you can on on:click={() => toggle()} in svelte which is more similar, but it isn't parsed and executed, it is a pointer to an anonymous function which is directly executed.
on:click={toggle()} in svelte would run the function immediately (probably not what you want) and return the result as the handler for the on:click
so quite different, really.
<div onclick="toggle"> has existed since the dawn of JavaScript in Netscape Navigator 2.0 Beta Gold. Your complaint about the syntax is in fact baked into the foundations of the web.
"bad" is subjective I guess but "Frankenstein" can equally be applied to ".svelte" & ".jsx" - both are non-standard amalgamations of imperatives with markup. In my mind the qualitative differences here end up being in parser support (jsx as a js language extension, svelte as... I'm not sure... not quite a HTML extension but closer to it I guess) and output consistency: this is either dynamic output by the node server in Svelte's case, or perhaps a multifile static bundle with Sapper/SvelteKit; that bundle taking various forms depending on your bundler chunking plugin configs, etc. JSX in contrast is a line-by-line one-to-one simply defined translating to basic native JS render calls: it's eminently auditable and will work with an infinity of preexisting testing/parsing tools that support basic JS.
> I have yet to find a greenfield React project with more than a few developers over a few years that didn't turn into a big ball of mud that only the original developers could understand (at best).
I've seen this with Svelte and React in relatively similar measure (I've seen hundreds of large React projects, some elegantly structured but most a mess. I've seen <20 large Svelte projects, all much much younger, all but 1 a complete mess). All in all this is a problem with the development/developer landscape and not either individual project dependency. Contributor scale is a hard problem.
Which is completely useless because your website doesn't work anyway