top | item 19719118

Svelte 3: Rethinking Reactivity

639 points| uzername | 7 years ago |svelte.dev | reply

179 comments

order
[+] mwcampbell|7 years ago|reply
From the tutorial:

> Svelte is giving us a warning:

> A11y: <img> element should have an alt attribute

> When building web apps, it's important to make sure that they're accessible to the broadest possible userbase, including people with (for example) impaired vision or motion, or people without powerful hardware or good internet connections. Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you if you write inaccessible markup.

Thank you! We accessibility advocates have wanted this kind of checking to be built into mainstream development tools for years. I hope Svelte becomes popular for this reason alone.

[+] mediumdeviation|7 years ago|reply
For what it's worth, Create React App is bundled with eslint-plugin-jsx-a11y which will give you the same warning
[+] phailhaus|7 years ago|reply
Eslint already warns you about issues like this, and is framework-agnostic. Does Svelte just use eslint under the hood? Otherwise you risk fracturing the ecosystem with framework-specific a11y requirements.
[+] tux3|7 years ago|reply
I'm really impressed that the release announcement starts by explaining what Svelte is. It's a little thing, but it's appreciated.
[+] keerthiko|7 years ago|reply
It's really not a little thing. The number of blog posts that talk about why version N+1 of X is great, assuming I know what X or version N did is stupid, and I am immediately churned out.
[+] bjz_|7 years ago|reply
Yeah, I first saw this approach taken by the Rust announcements in the early days. It's a great demonstration of empathy to the reader!
[+] SlowRobotAhead|7 years ago|reply
Agreed. I really appreciated him not assuming I know -fucking everything- and his WHAT included the WHY. ‘WHY’ (intent) is far more important an is missing from many different technical industries.

Tell me how you intend it to be used and I’ll see if that matches what I think I want (miss-wanting a different topic!).

[+] metamet|7 years ago|reply
Agreed. It's refreshing to not first need to open a handful of tabs in order to find my bearings.
[+] jashkenas|7 years ago|reply
Congratulations on the launch, Rich! It's looking like we're really starting to approach the form and function of what "a language to build the web" ought to be.

One small question about some of the pragmatic choices in Svelte 3: What was the decision process behind choosing to smuggle the new reactive features under a "standard" JavaScript skin? ($:, export let, etc.) Is it just to avoid needing to rewrite all existing JS tooling — parsing, syntax highlighting, linting — or is there something deeper going on?

[+] rich_harris|7 years ago|reply
Thanks Jeremy! As I've expressed elsewhere, observablehq.com provided important inspiration. I've also been influenced by your own comments in the past about a language for building web apps.

It's exactly that — there's so much tooling in the JS ecosystem that we can lean on, and by inventing new syntax we'd be throwing all that away. It'd be great if we could do `prop answer = 42` and `a <= b`, but it's just not worth it — once you get used to `export let` and `$: a = b` it quickly becomes second nature, we've found.

[+] bauerd|7 years ago|reply
"The magical disappearing UI framework" was a much better tagline than "Cybernetically enhanced web apps" …
[+] machiaweliczny|7 years ago|reply
Nice handling of reactivity - I think this should already be in language as well.

I'm not sure I like this single components approach and embedding JS in HTML.

The problem with this is that it's too frameworkish.

The big benefit of JSX/React rendering is that it's composable and declarative (as it's just functions), but it's also simple to get - render just returns wanted structure, given the state and you can use simple assert to verify that.

Solutions like angular/vue/svelte rely on custom template parsing which IMO sucks, because it's hard to extend/test without specific template compilers. JSX in contrast is embracing language.

I think that render functions written like in react and data reactivity is the simplest approach to describe application. Seems like VueJS with JSX is closest to this right now.

It would be cool to keep similar API but maybe use compiling to have smaller bundle/older browsers support/different platform support etc.

To be clear by similar API I mean just pure JSX components, where you plugin reactive data, that could be tested without any frameworks and without rendering. This is the simplest way, yet nobody build it yet - MobX + pure React components is close to this (problem is that still rendering is done by React, so rendering isn't most performant - depends on components hierarchy) - with compilation/integration you could make it more performant, but I would keep declararive nature and simplicity of JSX.

[+] lhorie|7 years ago|reply
> it's hard to extend

This is actually a feature, considering what Svelte does. I know of more than a few efforts to implement similar compile-time production of low level procedural code from React components, but so far nobody's been quite able to do it. And this is despite these efforts coming from some very smart people. The reason this is so hard to do for React is precisely because Javascript is a huge target with a ton of bizarre quirks and edge cases.

> To be clear by similar API I mean just pure JSX components, where you plugin reactive data,

I think Solid.js is the closest thing to this atm. Not React-based though.

[+] atiredturte|7 years ago|reply
I'm currently working on a giant React frontend codebase and it's baffling how slow certain simple things are for our users. Yes it makes it easier for us to reason about, but performance should be able to scale without hacks.

Svelte seems to show a lot of promise, but I have a few things that I'm not 100% on.

1. How are the higher level abstractions for Svelte? Any framework can be easy for simple applications, but how easy will this be to reason about as we get to larger applications? React deals with this through a semi-functional mindset. What does Svelte offer?

2. Is there any plans for facilitating incremental rollouts? Changing your application to an entire new framework is not always worth it, and is greatly difficult. I could imagine Svelte being incredibly useful for large-scale, performant applications. However, unless it can be incrementally rolled out, then I can't see how the biggest players will be able to utilise the power of Svelte.

I'd love to see the game changed in web frameworks, and I love the idea of using compilers where possible. If anyone could answer these queries, I'd be very much grateful.

[+] eliseumds|7 years ago|reply
How easy would it be to "hook into" Svelte's compilation pipeline so that users can create their own optimisations? I ask that because I work in a huge codebase with many layers of component abstraction and performance is starting to take a hit. For example, most of these components:

  <Box flex flexAlignItems="center" marginTop={5}>
    <Heading level={2} caret="down">
      Profile info
    </Heading>
    <Media>
      <Avatar id={avatarId} size="small" lazy />
      <Media.Block marginLeft={2}>
        {displayName}
      </Media.Block>
    </Media>
  </Box>
would be compiled into their simplest forms:

  <div className="flex flex-align-items-center margin-top-5">
    <h2>
      Profile info <span className="caret-down" />
    </h2>
    <div className="media">
      <img src="https://www.cdn.com/avatar/{avatarId}" className="avatar-small" lazyload="on" />
      <div className="media-block margin-left-2">
        {displayName}
      </div>
    </div>
  </div>
I believe the technique is called "component folding". I tried to do it with Babel but it's a real pain.

Thanks for putting so much work into exploring alternative ways of making the web faster, because, at the moment, it still requires an immense effort.

[+] artemir|7 years ago|reply
Yeah, I search the same solution. Because, I don't like write CSS and prefer use component abstraction layer, which allow write much simple code and it's really nice to read
[+] makkesk8|7 years ago|reply
I recommend everyone to take a look at the talk linked in the article. It gives you a good overview of how awesome svelte is and how easy it is to use.

I chose vue over react for simplicity and I'll be damned if I don't choose svelte over vue for the same reason and more after this talk.

[+] revvx|7 years ago|reply
Immer.js (a library to work on data structures, not a framework) uses a similar concept, using Proxies.

The gist of Immer is that your framework needs immutable structures, but you want to interact with them imperatively.

It's very interesting, and a reversal of the traditional "functional core, imperative shell" architecture.

https://github.com/immerjs/immer

[+] Tade0|7 years ago|reply
Hooks have some intriguing properties, but they also involve some unnatural code and create unnecessary work for the garbage collector.

Thank you for pointing this out. To me hooks were always a way to solve problems in React that wouldn't be there if it weren't for React. They help, but come at a cost which barely anybody seems to talk about.

We really want to add first-class TypeScript support.

Yes, please!

[+] kylecordes|7 years ago|reply
I'm excited about the updated Svelte. Although it is currently nowhere near being in the top handful of frameworks by adoption, it has some very forward ideas. Most prominently, look at the first main value proposition on its website:

“Write less code”

Svelte has a ways to go to catch up with the leaders on popularity and future breadth, but it is focused on the right problem: reducing the cost/size/effort of making things.

[+] Vinnl|7 years ago|reply
Funny: problems I think are important are "ship less code" and "read less code" (and perhaps "require reading less code to understand what's going on"). The writing part is not something I've considered to be especially problematic, thus far.
[+] gedy|7 years ago|reply
Since you are reading here Rich Harris; while I really admire your solutions, one weak point with Svelte seems to be a clear unit testing solution, or at least docs last I looked. I also noticed this with Ractive, and feel it weakens these in the eyes of many businesses considering these tools.

I know it's a solved/solvable problem but it feels like better docs and samples in quick start guides would help.

[+] IshKebab|7 years ago|reply
This is roughly how QML works too right?

> Cybernetically enhanced web apps

That is pretty terrible! It seems to me that the main think that distinguishes Svelt is that more work is done at compile-time? Why not a slogan that says just that?

"Compile-time optimised reactivity." or "Low overhead reactive web apps" or something like that. Cybernetics is nonsense waffle.

Anyway good luck! Seems like a better approach than shadow DOM etc.

[+] dhbradshaw|7 years ago|reply
Agreed: compile-time optimization is a pretty good pitch. Rust and Typescript and Haskell have done all the PR necessary for this pitch; you have a prepared audience.
[+] vladimir-y|7 years ago|reply
> Cybernetically enhanced web apps

Is not AOT compilation is a more traditional name for such stuff?

[+] evangow|7 years ago|reply
One area where the virtual DOM seems to be important is for rich text editors, where the VDOM can basically take the input, diff it using an immutable structure, then render it to properly structured HTML.

An example use case where this would be valuable: a user hightlights text, bolds it, then highlights it again plus some more text, and bolds it. A naive approach would have: <b><b>This text is bolded</b> plus I bolded this</b> when what you want would simply be: <b>This text is bolded plus I bolded this</b>

Libraries like DraftJS and SlateJS use immutable data structures to parse the input/formatting in the VDOM and reconcile them into "blocks" (basically javascript objects containing the formatting) that deduplicate formatting.

The talk below on DraftJS is pretty good.

https://www.youtube.com/watch?v=feUYwoLhE_4

What's the recommended way to handle a rich text application in Svelte? Is there anything like the above for Svelte?

[+] ChrisCinelli|7 years ago|reply
I tried Svelte/Sapper a few weeks ago. It is definitely not the new framework of the month that come and go.

I love it. I cannot believe how fast the app load on both first and second time visits. 100% in lighthouse.

I think Svelte is the way to go! I hope the community will accelerate and eventually catch up with React and Vue!

[+] simplify|7 years ago|reply
Mithril.js has been doing plain javascript variables for years :) Basically, React's decision to use setState is an overoptimization. Mithril (and flutter, interestingly) opts for global redraws, greatly reduces end-user code complexity while still being fast for most all cases.
[+] olah_1|7 years ago|reply
Thanks for mentioning Mithril. When I saw Svelte example output js, I thought it was actually a better developer experience layered on top of Mithril. (Mainly because of the similar m() mounting function)

```

function create_fragment(ctx) { var h1, t0, t1, t2;

return { c() { h1 = element("h1"); t0 = text("Hello "); t1 = text(name); t2 = text("!"); },

  m(target, anchor) {
   insert(target, h1, anchor);
   append(h1, t0);
   append(h1, t1);
   append(h1, t2);
  },

  p: noop,
  i: noop,
  o: noop,

  d(detaching) {
   if (detaching) {
    detach(h1);
   }
  }
 };
}

```

[+] thunderbong|7 years ago|reply
Totally agree.

Multiple frameworks have done this for many years, but nobody will listen as everyone is interested in the next new, shiny thing.

I do like Svelte in its latest incarnation though, especially when it integrates with Sapper.

[+] aboodman|7 years ago|reply
Flutter does its own painting. It's different, and closer to a game engine than what React is doing. That results in different tradeoffs.
[+] acjohnson55|7 years ago|reply
Their interactive tutorial with sandboxes is really impressive. That's a great onramp into actual usage. It might also be cool to have a good way to "eject" the sandbox into a functional local build.
[+] rich_harris|7 years ago|reply
Anything built inside https://svelte.dev/repl has a 'download' icon (top right) which gives you a zip file containing a ready-made project. We basically just need to have a way to take you from tutorial/example pages to the equivalent REPL page — it's on the TODO list :)
[+] saabi|7 years ago|reply
That will be possible soon.
[+] nojvek|7 years ago|reply
I went through the tutorial. It’s quite confusing. I’ve been doing front-end SPA apps for about 10 years now.

The framework that has blown me away with it’s simplicity and elegance but power is snabbdom.

It’s small, it’s fast, it’s modular. You can use it with jsx, you can use it with webcomponents if you want. You can type it with typescript. Animations check, custom module extensions, check.

As the recent experiments in wasm has shown, you can make extremely fast vdom diffing that is memory allocator friendly.

So my bet in the future is this. Vdom will be here for a while. It’s simple, elegant and we’ll figure out how to make it faster with newer tricks.

More non web UI frameworks will use similar approaches. React Native is paving wave here but I can see desktop apps and terminal apps embrace the same concepts too.

View as function of state is a very powerful paradigm. State being a simple dumb old nested object. No magic tricks.

Svelte feels too magical. Vue has same issues. It’s hard to reason with magic when you hit edge cases.

You ideally want a simple model in your head so you can build really complex apps by connecting simple axioms of logic.

[+] PudgePacket|7 years ago|reply
The whole point is that there is even less magic than react, vue etc. If you have time I'd strongly encourage you to watch the video shown in the post.

https://svelte.dev/examples#dom-events Look at the compiled output (the "JS output" tab), it's so readable and stepping through it with a debugger is actually possible for mortals unlike trying to step through code using react (I know, I've had to do it..).

[+] dbrgn|7 years ago|reply
Did you watch the video embedded in the blogpost? Rich Harris talks about both speed (including the Dodrio vdom in Rust/WASM experiment) and magicalness.
[+] anderspitman|7 years ago|reply
This is really cool. That said, I noticed that it cites performance vs vdom as a selling point. Something I've been wondering lately is how big of an issue is UI performance for most web apps really? So many of the little apps and prototypes I develop aren't hurting for performance. It seems to me the industry made a huge leap from JQuery/Backbone/etc to reactive/vdom. But declarative UIs and virtual doms don't solve exactly the same problem; they just go well together. Are there any frameworks out there that provide a JSX/VueSFC/hyperscript development experience, without adding the complexity of a virtual dom implementation? I think developing UIs in a declarative fashion is a big win, but having a virtual dom seems like it should be treated more like an optimization to me.
[+] rich_harris|7 years ago|reply
> Are there any frameworks out there that provide a JSX/VueSFC/hyperscript development experience, without adding the complexity of a virtual dom implementation?

Svelte is intended to be exactly that!

Whether performance is an issue depends partly on the kind of app you're building. In my line of work (producing interactive data visualisations etc) it absolutely is. As I talk about here, it's going to become even more important as the 'embedded web' becomes a thing: https://youtu.be/AdNJ3fydeao?t=1498

Bonus thoughts on virtual DOM: https://svelte.dev/blog/virtual-dom-is-pure-overhead

[+] writepub|7 years ago|reply
It's really surprising that people put faith in virtual Dom implementations, when browsers have been optimized for decades for efficiency. With the right batching strategy that minimalistic libraries like FastDom [1] offer, there's no real reason to use the virtual Dom.

A frequent argument for the use of vdom has been that it reduces Dom trashing. I am willing to bet that if a vdom library has figured out what elements don't need updating, the browser's Dom implementation tuned over decades has that logic built-in. So go ahead and trash the Dom, but batch your updates and the browser's logic will likely not trash more than necessary. And since that logic is implemented in an AOT compiled language, it probably is much faster than a js v-dom

[1]: https://github.com/wilsonpage/fastdom

[+] ummonk|7 years ago|reply
Large React apps get slow very easily once the component density gets high in a complex web app. Part of the reason for that is actually the overhead of a virtual DOM.
[+] wontoncc|7 years ago|reply
I'm wondering how good Typescript support is. Can I use Typescript in the component script?
[+] rich_harris|7 years ago|reply
Sort of, via preprocessing, but you won't get any real benefit from it at present. There are two barriers: the compiler itself needs to become TS-aware, and we need to teach editors like VSCode how to typecheck inside <script> blocks.

It's very much on the radar (I'm a TS convert, personally — Svelte itself is written in TypeScript), we just need to get round to it. The version 3 rewrite was largely about laying the foundations for TS support.