Hacker News new | past | comments | ask | show | jobs | submit login
Svelte 3: Rethinking Reactivity (svelte.dev)
639 points by uzername 59 days ago | hide | past | web | favorite | 179 comments



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.


For what it's worth, Create React App is bundled with eslint-plugin-jsx-a11y which will give you the same warning


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.


Accessibility requirements for the web have a centralized source in the WCAG. As long as linters/checkers conform to that, it doesn’t seem like it should be a source of fragmentation.


I'm really impressed that the release announcement starts by explaining what Svelte is. It's a little thing, but it's appreciated.


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.


This is basically v1 though, so it's a bit different.


Uh, it's v3... People are using both 1 and 2 in prod...


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!


In particular, I think this is a recognition of the fact that people these days don't follow random projects, but they do follow social media feeds and news aggregators like HN or Reddit. So an average reader may come to the post not because they know and care about Svelte, but because the link being on their favourite aggregator lent it credence as something worth reading.


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!).


Agreed. It's refreshing to not first need to open a handful of tabs in order to find my bearings.


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?


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.


> I've also been influenced by your own comments in the past about a language for building web apps

Hey Rich have you seen Imba?

http://imba.io/

It's not reactive, but it doesn't need to since everything is memoized. I think it's interesting that they made their own language to solve the front end problem.

They used it to build https://scrimba.com/ which is pretty awesome.


I have seen it, yes. I'm impressed by the ambition, though I think that in the long term it's better to work with the grain of the platform by extending the web's existing languages rather than creating a new one.

Memoization certainly makes Imba a lot faster than VDOM-based frameworks. Of course, it's only really beneficial when not many things have changed!


Can you say more about this?

Your article says about `count += 1` that "we can do all this without the overhead and complexity of using proxies or accessors. It's just a variable."

But it's not just a variable; it's a magic variable that $$invalidates its contents. I'd be much happier to write `state.count += 1` and allow my debugger to step into the proxy in dev mode, but then have the production compiler convert the proxy into a direct call to $$invalidate to minimize runtime overhead and support legacy non-proxy browsers.


Firstly, that's more code you're having to write (and object property names don't typically get mangled, so you'll end up shipping more code as well as writing more code). Write less code! https://svelte.dev/blog/write-less-code

You can easily debug reactive variables, either using the `{@debug ...}` tag in the template (https://svelte.dev/examples#debug) or by using `debugger` in your script tag (https://svelte.dev/repl?version=3.0.0&gist=adc35e969343aad60...).


"The magical disappearing UI framework" was a much better tagline than "Cybernetically enhanced web apps" …


Completely agreed -- taglines and marketing speak are so important especially in the dev community where they're often overlooked.


Yeah as someone who hasn’t heard of this before the first tagline would be far preferable.

It gives an inkling of the functionality and most importantly avoids “cybernetically” which makes the framework sound kooky.


Magical disappearing makes it sound like a cheap parlor trick.


To me it’s worse. It sounds like a framework whose creator has run off and deleted the github repo.


Or an Initial Coin Offering.


Also includes the word "magical", which is risky.


We certainly debated this one over in the Discord channel...


Just to bikeshed some more, why not recall the definition of svelte? Something along the lines of "the attractively thin (web app|UI) framework".

I didn't even think it was an English word before I watched Rich's (great) talk.


What about "Faster web apps with less code?"

or "Faster, smaller, web apps?"

They seem to be the main benefits for using Svelte.


"Less code" implies less authored code, which may be a benefit of Svelte (is it? I haven't been able to use it much but it's on my radar) but doesn't necessarily map to its technical goals (less built code, less runtime processing).

(Quick example: the countless hello world projects that result in >100KB bundles)


Authoring less code is definitely an explicit goal: https://svelte.dev/blog/write-less-code


Ryan Tomayko would agree that's a noble goal!

http://lesscode.org/


Obligatory fanboy comment: it seems that every project you create moves web dev in a better direction, and you don't seem like a bad chap either!


Thank you, that means a lot!


You're not just moving web dev in a better direction, but also fact and data based journalism and visualization! I first learned of Svelt and Rollup (and became your fan) when I asked how you made that great NYT article, The Follower Factory! I'm glad you've kept working on Svelt, and I can't wait to see what you do next.

https://www.nytimes.com/interactive/2018/01/27/technology/so...

https://news.ycombinator.com/item?id=16247571


Deliciously edible fully organic packaging?

Ouroboros: the tail recursive self devouring snake!


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.


Check out my library DOM Expressions(https://github.com/ryansolid/dom-expressions#readme) It's almost exactly what you are talking about. The libraries I've written on top (Solid.js, MobX JSX, and KO JSX) are among the fastest on the JS Frameworks Benchmark(https://krausest.github.io/js-framework-benchmark/current.ht...). The future is already here.


> 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.


Mobx-state-tree is a really nice balance of state management that also is compatible with all the nice Redux browser tools https://github.com/mobxjs/mobx-state-tree


Svelte exposes a [preprocess function](https://svelte.dev/docs#svelte_preprocess) that (in theory?) you could use to preprocess markup JSX-style.


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.


Our vision for how to build large apps with Svelte is best represented by Sapper — https://sapper.svelte.technology — which is a Next.js-style framework. Right now it's a bit out of date, we need to spend some time bringing it in line with Svelte 3. That'll happen fairly soon.

Svelte is pretty well suited to incremental rollouts, because it doesn't have a chunky runtime foundation — it's not as though you have to ship two full frameworks simultaneously. There are some community-maintained adaptors for using Svelte components inside apps for other frameworks, I believe. You basically have to start at the leaf components and work your way in. An alternative approach would be to compile Svelte components to custom elements instead, since they can (in theory!) be used anywhere.


> 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.

What's the underlying reason for the slowness?

React applications can definitely be written to be performant without resorting to "hacks", typically using immutable data structures (that support reference equality checking) in combination with judicious use of PureComponent/shouldComponentUpdate/React.memo. Also using something like react-virtualized/react-window for large lists/grids.


I've never worked with React, but I have worked on giant AngularJS (1.x) apps and medium-sized Vue apps. I've only seen performance issues on pages with long repeated lists that create a lot of $watchers. This is fairly straight-forward to solve, and I know that Vue and Angular are both a lot smarter about tracking changes than AngularJS was.

Is React more difficult to keep responsive as an app grows? What sort of UI paradigms lead to poor performance? Just the phrase "using immutable data structures (that support reference equality checking) in combination with judicious use of PureComponent/shouldComponentUpdate/React.memo" makes it seem like you need lots of in-depth React knowledge and additional packages to write a performance React app.


React's default behavior is that when a component re-renders, React will render all of its children recursively, even if they are receiving the exact same props as before.

In many cases, these re-renders return the same render output as the previous render, which means that no changes need to be made to the DOM. These renders are referred to as "wasted", because React went through the work to ask your component "what do you want the UI to look like?" and diffing the output, when nothing actually was going to change.

The two key aspects of optimizing performance in a React app are:

- Decide if the props and state for this component have meaningfully changed

- Tell React to skip the rest of the rendering process for this component (and therefore skip the rest of this subtree as well)

The standard approach for checking for changes is simple reference checks: `prevProps.a === props.a`. For larger amounts of data, this assumes you've updated that data "immutably", by making copies and modifying the copies instead of the originals. This can be done with plain JS objects and arrays, it just can take a bit more diligence. (Libraries like Immer [0] can help with applying those updates immutably.)

For the "skip rendering" part, React has offered several APIs over time, but they all basically boil down to "do shallow comparisons of data, and bail out if they're the same":

- The old / deprecated `createClass()` API allowed use of a `PureRenderMixin`

- Classes have a `shouldComponentUpdate()` lifecycle method where you can implement whatever custom comparison logic you want, and return `false` if the render should be skipped

- Since the typical comparison in `shouldComponentUpdate` is a shallow equality check of both props and state, the `PureComponent` base class was added that does that by default

- More recently, the `React.memo(MyComponent)` API was added to allow wrapping any component (class or function) with that same bailout behavior.

All of those are actual React APIs, not separate packages.

All that said, the React team advises that you should just write the app first, _then_ profile it later (in a production build!) to see where the key bottlenecks are and just optimize those. In most cases, you probably don't even have to do anything - performance will often be sufficient as-is.

React's DevTools have a performance profiling tab [1] [2] that helps show which components rendered for a given update, which makes it a lot easier to track down unnecessary renders. The community has also created various "why did you update?" libs that log unnecessary renders.

[0] https://github.com/mweststrate/immer

[1] https://reactjs.org/blog/2018/09/10/introducing-the-react-pr...

[2] https://www.netlify.com/blog/2018/08/29/using-the-react-devt...


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.


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


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


Yep, and Svelte <3 Immer — they work nicely together.


Great work, just looking in to Svelte now after reviewing your latest release and video. First thing I looked for was routing, and I see Sapper is essentially batteries-included solution to using Svelte.

Will these always be separate libraries? Is Sapper basically the create-svelte-app for your framework? What's the roadmap for Sapper and integrating Svelte v3 changes?


Bringing Sapper up to date is the next big task. In some ways yes, it's a bit like create-svelte-app, though a closer reference point if you're versed in the React world would be Next.js.

We've also mulled creating a React Router equivalent, for people who prefer components-as-routes to files-as-routes.


I'm a huge fan of immer. I use it in all my React projects. It makes writing reducers a lot easier. Highly recommended.


Yep, we use it in our new Redux Starter Kit package to drastically simplify immutable update logic in reducers:

https://redux-starter-kit.js.org/api/createreducer


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.


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!


I've created two project as a POC for typescript support https://github.com/farhan2106/svelte-typescript https://github.com/farhan2106/svelte-typescript-ssr

Basically, I separate out the <script> & <html> section into two files. The <script> part is generated from typescript and combined later before sending it into the svelte compiler.

I am currently working on a gulp build file to streamline the process.

Let me know what you think.


Hooks solve a definite problem that I’m not sure is limited to React, but at the end of the day they feel too much like magic to me.

Reasoning about hooks is hard.


I find this interesting. Could you give an example of a case you find hard to reason about?


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.


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.


Allow me to try and convince you of its importance :) https://svelte.dev/blog/write-less-code


I actually read that just before this comment :)

Edit: Some more clarification about why the arguments don't hold for me.

- More code = more bugs

I think code that is harder to understand leads to more bugs, but more characters typed does not necessarily directly result in more bugs, as far as I know.

- Writing code takes more time

Again, it's not the typing that takes time, but thinking of which code to write. If I have to type more, but there's less for me to keep in mind while typing (i.e. lower cognitive load), I'll be faster at that.

As said: yes, readability is important, but that's a different value than "write less code".

I'm trying not to make a judgment about Svelte here specifically since I haven't worked with it yet, and the general concept (of being a compiler rather than working during run-time) appeals to me. That said, concepts like bindings do scare me - with e.g. `useState` I know that the only places that can change `a` are those that call `setA`, whereas it appears that with Svelte, it can also change e.g. in response to `bind:value` attributes? I'm (perhaps misguidedly) afraid that that's saving a few characters at the cost of readability.


> more characters typed does not necessarily directly result in more bugs, as far as I know

Most of the discussions I could find on the topic before writing that post suggested that the error rate per thousand lines of code is surprisingly constant across languages, which suggests that more characters typed does result in more bugs. I learned that from the internet though, so take it with a grain of salt!

It's true that `bind:value={foo}` offers another way to change the value of `foo` besides `foo += 1`, since at that point you're explicitly opting in to two-way binding. If you prefer, you certainly can do the `on:change={handler}` thing instead, but as I argue in the post I think that's less effective at capturing the intent of your code (and gives bugs more places to hide). This is definitely a subjective area though.


> Most of the discussions I could find on the topic before writing that post suggested that the error rate per thousand lines of code is surprisingly constant across languages, which suggests that more characters typed does result in more bugs. I learned that from the internet though, so take it with a grain of salt!

It's an interesting subject, but I'd like a causal explanation rather than just the correlation. For example, this would imply that TypeScript code would be more buggy than its Javascript equivalent, since it's the same code I'd write otherwise, with additional annotations. (Then again, there is some code, like null checks, that I don't have to write with TypeScript, so perhaps that evens out.)

> I think that's less effective at capturing the intent of your code

It's been a while since I've worked with Angular.js, the last framework I used with two-way databinding, but now having this conversation I think I recall the main reason it was confusing. A pattern that would sometimes arise is e.g. for a component to receive data through a two-way databinding from its parent, and then likewise passing that on to a child. That could make it very hard to trace where a change was coming from.

It might well be the case that it is far less problematic when e.g. only used to bind form values. Again, I'd have to try it to get a proper feel for it, so I'm looking forward to doing that.


> It's an interesting subject, but I'd like a causal explanation rather than just the correlation.

A large benefit with less code is about the signal/noise ratio. If you need plenty of boiler plate logic, you will have less signal that you can physically read & mentally process at a given time. We naturally ignore the noise, but the noise takes screen space & miscategorizing noise leads to bugs.

Less code leads to less bugs, especially high-level bugs, because the programmer can see more signal at a given time, thus being exposed to a larger system.

The study that Rich mentioned could be interpreted as relating to the comprehension of the code, where more code inherently means the system has more information & is more difficult to comprehend.

Re: two-way binding, the data flow is inherently confusing whether you use imperative or declarative logic. Do you want a clear concise representation or do you want to spread out the implementation over more code/files?


Absolutely, and "higher signal-to-noise-ratio" is something I'd count as a selling point. However, I don't believe fewer characters necessarily result in a higher ratio.

So in the case of two-way data binding, if I'm trying to trace how a certain value was be modified, data flow in the opposite direction might count as "noise", in terms of extra cognitive load.

Again, this might not be something that is the case for Svelte, but it's what I observed in Angular.js.


Yeah I don't know. More noise sure but I fear Svelte just misses the point. I'd write a rebuttal but I sort of already have: https://medium.com/@ryansolid/what-every-javascript-framewor...


What are your opinions of Go where it is the general idea to only have 1 way to do something, and make that way the best way?


I have not used Go, or even looked at it, so I can't really give a well-reasoned comment about it. As for the general principle of having just one way to do something: I don't think that's a general rule that I'd prefer, because I don't believe there's always a clear best way.

I think my problem with two-way data binding is not so much that it's an additional way to update a value, but that it doubles up as reading and writing a value, and with that makes code somewhat harder to read. However, as I noted in response to Rich, that might not be a problem if that is only limited to variables bound to forms, but I'd have to try it to get a better feeling for that.

But I'm getting off-topic, so the answer is: I don't really have an opinion about Go, but the general principle you describe is not one that attracts me.


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.


You're totally right. This is good feedback — we'll have a think about how we can best address this.


I admire Rich Harris' work as well. 4 years ago I was picking my first SPA framework. Narrowed it down to Ractive and Vue. Picked ractive, it had a beautiful documentation and tutorial. Still have an app in production based on ractive. But author abandoned it. Then vue 2 took off. I didn't have a choice but switch. Recently I started playing with Svelte/Sapper again. I like it a bit better than vue for some reason and was looking to use it in the next project of mine. So svelte 3 comes at right time for me.

The author is a brilliant developer, but he should narrow his focus on Sapper/Svelte now, beside which he has many other projects (rollup, etc...)


> But author abandoned it.

To be clear though, Ractive is still under development by other maintainers: https://github.com/RactiveJS/Ractive.

> he should narrow his focus

Not to speak for him, but I think Rich is an "idea guy" and we'd all miss out if he were throttled to just one thing :-)


I still use ractive for production apps today, and have legacy ractive apps that are from 2013’ish running great


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.


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.


If you like cool sounding sleek modern curved aluminum nonsense waffles, there's always Buckminster Fuller's classic:

Dymaxion: dynamic, maximum, and tension -- maximum gain of advantage from minimal energy input.

https://en.wikipedia.org/wiki/Dymaxion

Simply zip all your content into a sleek .ddu file and upload it to the server:

https://en.wikipedia.org/wiki/Dymaxion_deployment_unit


> Cybernetically enhanced web apps

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


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?


Rich text editing is possibly a special case, though the right person to ask about that would be Jacob Wright (https://github.com/jacwright). He's the creator of https://www.dabblewriter.com (which uses Svelte) and a Svelte contributor, so he probably knows more about this topic than just about anyone else!


Thanks for sharing! Looks like Jacob has open-sourced a svelte-based rich text editor based on Quill. Link below for anyone who is curious.

https://github.com/typewriter-editor/typewriter


I'd argue that a rich text editor tied to a framework is inflexible, and possibly inefficient. You want a rich text editor to be good at one thing, editing, and not be concerned with how it's invoked.

A good editor would be standalone, with wrappers to make it callable from a framework of your choosing.

Most good rich editors implement their own internal Dom to achieve uniformity across browsers. DraftJs, Quill, Trix... use this strategy. There's nothing unique to react-Dom that benefits rich text editing


An important feature of a good framework is to be able to break out when needed to do normal JS, so I imagine you’d do that and grab a regular editor component.


If you need a rich text editor, I would just plug in a framework-agnostic rich text editor (e.g. ProseMirror).


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.


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..).


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.


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.


> 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


Thanks for the article link; that was an excellent read.

I don't think my post was very clear. I agree that the run-time complexity of svelte is much better than a vdom framework, but it seems like you're just trading that for build-time complexity. Maybe that's the only way to achieve what I'm talking about though. At some point you have to translate from immediate mode to retained mode if you're rendering to the dom.

I also work in interactive visualizations. I think this is one of the areas (in addition to games especially) where vdoms quickly fall short. Once you start animating a lot of SVG elements, it doesn't matter much what framework is under the hood; it's going to crawl. Canvas/WebGL is the only real solution I'm aware of. Does svelte somehow provide a significant speedup in these situations? I obviously need to read up more on what your compiler is actually doing.


My view on this is that complexity, like energy, can only really be converted from one form into another. Normally the distinction is between runtime complexity and cognitive complexity — the result of hand-optimised imperative code. In other words, the classic trade-off between developer experience and user experience.

Svelte's claim is that converting it into build time complexity is in fact the only sensible thing to do. It doesn't really matter how much complexity is involved in `npm run build` if it means that DX and UX are no longer in tension.

But to answer your point about SVG, Svelte has to obey the same fundamental constraints as any other code, so you will eventually hit performance issues (though you may enjoy this demo https://youtu.be/AdNJ3fydeao?t=1138). One avenue I'm currently exploring is whether the same declarative/compiled model can be used as a wrapper around WebGL APIs, though it's very early days.


> My view on this is that complexity, like energy, can only really be converted from one form into another.

I like that. I'm definitely going to have to think on it some more.

> It doesn't really matter how much complexity is involved in `npm run build` if it means that DX and UX are no longer in tension.

As long is it doesn't break. I think Vue has a fantastic developer experience. As long as everything works you have incredible leverage as a developer. But the first time I tried to pass it a large nested object I lost many hours figuring out that I needed to call Object.freeze to prevent it from setting up reactive hooks on the whole thing (once set the data was static).

> One avenue I'm currently exploring is whether the same declarative/compiled model can be used as a wrapper around WebGL APIs, though it's very early days.

Keep us posted. I've done some experimenting on this myself. I built this[0] using a lisp-ish markup language I threw together. Think SVG with built-in support for defining and composing sub-components. The language compiles down to canvas calls at runtime. That version renders to 2d canvas, but I started a WebGL implementation that I haven't finished yet.

[0] https://anderspitman.net/apps/hardware-bubblesort/


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


I was waiting for someone to post this. We have tried hyperhtml, various VDOM implementations like Vue and React, but nothing compares for our complex app. We use FastDOM however we are starting to realize it may in fact be causing some issues with write conflicts with third party scripts requiring DOM mutations. That said requestAnimationFrame which FastDOM also uses, can be majorly helpful for any thrashing. Curious what Rich thinks of FastDOM library or while I'm at it his opinion on (not a UI)..https://meiosis.js.org/


People used to look at me like I was crazy when I told them that React is nice, but you can actually write faster code with alternative methodologies. It seems like other engineers are coming around to this and creating these faster alternatives.

React made writing frontends generally better, but often slower and as rich_harris points out that it entails a lot of developer work to build and use optimizations to speed it up.


I like it. You can only hide so much comlexity in 600 bytes. Something like fastdom could probably facilitate what I'm talking about. Basically don't bother diffing, but only actually touch the DOM once per frame. So I guess in that case you'd have tons of "phantom writes" to fastdom as the state is reactively updated.


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.


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.


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);
   }
  }
 };
}

```


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.


Flutter does its own painting. It's different, and closer to a game engine than what React is doing. That results in different tradeoffs.


I'm wondering how good Typescript support is. Can I use Typescript in the component script?


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.


Svelte itself has been on my radar for quite a while - I think when proper TypeScript support lands, that will be the first time I'll actually give it a try for one project or another. The idea is intriguing, thanks for working on it!


Do you have any estimate on how much work that'll be? Do you think you'll be able to land TS support (including type-checking through the command line) within half a year, or is that a bigger thing?


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.


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 :)


That will be possible soon.


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!


> this.set is almost identical to the this.setState method used in classical (pre-hooks) React

It's an amazing reflection on the velocity of the web & JS ecosystem that React APIs prior to hooks, which were shipped all of 3 months ago, can be sincerely referred to now as 'classical' :-)


I think he means 'classical'as in class based. Just like you'd refer to 'classical' inheritance.


You might be right - I've never heard 'classical' used in that way, interesting!


You're both right — it's intended to be a slightly ambiguous low-key pun :)


Hey Rich if you're still lurking - I really like the Tutorial layout (even on mobile!) and how that all works. Is this something you built yourself or is there a re-usable component that I can use?


It was all built in-house by me and other members of the Svelte community. The playground widget is technically a standalone thing, but it wasn't totally designed to be used outside https://svelte.dev so may be a bit warty! https://github.com/sveltejs/svelte-repl (the code for the site itself is in the main project repo https://github.com/sveltejs/svelte/tree/master/site)


Interesting to see performance difference comparing to 2 version: https://github.com/krausest/js-framework-benchmark/issues/55...


I'm very intrigued by Svelte and I really hope that it will succeed. In that sense I also hope that this is the last major version, i.e. no more breaking changes. That would be fantastic!

Does anyone here have a major, non trivial app in production that's built on Svelte?


Pinefore is a frontend for Mastodon based on Svelte2, I've found it to be a great non-trivial example: https://github.com/nolanlawson/pinafore


Svelte looks amazing. Some questions that occurred to me:

- Does it work with TypeScript?

- How does it relate to other reactive frameworks, such as RXJS? Does it make sense to use them together or does the Svelte compiler invalidate the benefits of them?

- Does it work with any existing components?


- Is speed comparison going to include Angular with Ivy renderer enabled (and probably OnPush change detection strategy enabled)? It's also AOT rendering stuff that doesn't use virtual DOM.

- There is a lot of static code analyzing tools, like linters, that work with separate JS/CSS/HTML files. Does Svelte have to adapt all those tools in order to make them properly work with a single file component (.svelte file)?

- I believe enabling first-class TypeScipt support would bring more sanity to Svelte-based development.


Odd that they don't mention Angular amongst the component-based frameworks, as what they're describing sounds very similar to Angular's compiler and change-detection system.


Actually Angular does this with Zones which is a different Reactivity system.

This is actually quite similar to what PostSharp did with WPF where it injected INotifyPropertyChanged and WPF compiling its getters and setters.

Then it's also similar to KnockoutJS (inspired by WPF), MobX (inspired by Knockout) and Vue (also inspired by Knockout)


Zones is only responsible for triggering change detection caused by user/external input. It's possible to use Angular without Zones.


Svelte as a lot in common with Angular, arising from the decision to use a component compiler at build time. But culturally it appears most attention to Svelte comes from a React direction, so Svelte is most often described as a “diff” from React.

You could possibly predict the future of Angular and Svelte by comparing them and looking for ways to cross-pollinate.


I haven't used it yet but I really like the idea of Svelte, just how I really enjoy using Preact over React for certain projects.

One question about version 3. I was wondering if they addressed the issue of how a Svelte code base can grow in size larger[1] than a Preact based codebase the bigger it gets.

[1] https://medium.com/@chrisdaviesgeek/tiny-js-frameworks-preac...


Creator here. We get this question a lot, and should probably dedicate a blog post to it.

It's true that the incremental cost per-component is higher than with some frameworks. In theory, you hit an inflection point. In practice though this doesn't really happen, because by the time you get there, you should be code-splitting anyway — and each of your code-split chunks have a hard minimum size which is the size of the framework.

This article reinforces that finding by testing the 'RealWorld' project: https://medium.freecodecamp.org/a-realworld-comparison-of-fr.... It's based on an outdated version of Svelte but the broad strokes will be unchanged.

Of course, Svelte is about far more than just bundle size!


How does Svelte compare directly To more minimal Reactive libraries like most.js or flyd.js? Even MobX? Besides the dissapearing at runtime? It looks very cool I'd like to see how it performs with some complex DOM opps. Might mess around today.


Those are all libraries for state management. Svelte is a UI framework. It incorporates its own state management (https://svelte.dev/tutorial/reactive-assignments for local state, and https://svelte.dev/tutorial/writable-stores for cross-component state), but you can also wrap third party libraries if needed.


thanks for the response! Interesting that this article you linked did not include Preact in its tests but I do see what you mean.

Keep up the good work! I think Svelte is really cool. Like I said before, I like the idea of it. I am going to promote it to the rest of my team and hopefully we can give it shot on one of our next projects.


Yes, the release I've been waiting for. I started to dabble with Svelte v2 right before coming of v3 was announced.

Are web component going to happen with v3? I am trying to combine Python server app with Svelte enhanced HTML and got good results on v2. I noticed they are marked as todo: https://svelte.dev/docs#Custom_element_API


It's only the documentation that's a TODO, you can use them currently. Just pass `customElements: true` to the compiler and specify a tag, either as `tag: 'my-tag'` or in the component itself with `<svelte:options tag="my-tag"/>`.

TODO: make shadow DOM optional, and only auto-register if a tag is provided (currently it's required)


Ah ok. Great to hear!


Would you consider adding a way to set tag names in a component dynamically? I’ve found that to be incredibly useful in React, when you want to encapsulate some behavior but use it in different semantic contexts across an app.

Or is it possible already somehow? I tried to use

  <svelte:component this={“h1”} ...
but it doesn’t appear to support strings, just Svelte components?


Just components for now, but we have an issue for it: https://github.com/sveltejs/svelte/issues/2324


Amazing. I was working on a mortgage calculation app with graphs and dependencies upon dependencies as calculations depended on other calculations. It seems Svelt would have been so much better to use than React in this case and I'm seriously going to use it going forward. Great work.


Is the frustration meter shown in the talk video part of that original benchmark? Or is it something we could run on top of any page? I had a search around, but didn't find anything.



Thank you so much!


Congratulations on the release, Rich!

Minor suggestion: it should be easier to find how to get started (read install) for people trying to give Svelte a try. I had already played a bit with Svelte before but wanted to try v3 and the only thing I could find about how to install it was in https://svelte.dev/blog/the-easiest-way-to-get-started.


Agree, we can always improve onboarding. We have some simple instructions using `npx` on the homepage, but we'll try and signpost it better.


This is a great talk. During its discussion, I've seen some misconceptions about what Concurrent React is. I hope this thread will be helpful to someone who's wondering why we're continuing work on that approach: https://twitter.com/dan_abramov/status/1120971795425832961


Very cool. Would love to try this. Anything that pushes things into compilation has immediate appeal, and this thing is clearly explained.


What I think is really interesting is that the Virtual DOM was touted as the better abstraction when React came out (in comparison to Angular 1's dirty checking).

I think Svelte is doing a lot of things right (simple code, computing CSS animations, accessibility built in, focusing on a compiler versus a full on framework) and I can't wait until Sapper is updated to dig in.


> What I think is really interesting is that the Virtual DOM was touted as the better abstraction when React came out (in comparison to Angular's dirty checking).

I think the VDOM seemed to offer a maxima and people thought it might be a global one (even though in hindsight it seems like a silly proposition). Angular certainly hasn't exactly delivered on performance in any meaningful way that I know of, at least, so maybe the VDOM, even if it was a local maxima, was still the better of the two?

As a basis for a durable design and a way to move forward, clearly we have a better way, though, but that can only be illustrated by a project actually doing well at it.


I think VDOM made sense at the time because DOM elements come with so much overhead that dirty checking thousands of elements (in Angular 1's case) does not scale well.

I think the issue became that the VDOM creates some overhead that making very simple DOM changes can avoid altogether. From what I understand, Svelte sidesteps the VDOM and outputs the smallest amount of code to achieve the desired level of reactivity which might be the better abstraction.


> focusing on a compiler versus a full on framework

Angular goes a similar way, just look up Ivy renderer on the internet.


That's very interesting! Stopped paying attention after Angular 2 was released... will take a look, thanks for the info!

Edit: It looks like the goals are a bit different with Angular's focus on Typescript (Svelte let's you do this but is not entirely focused on Typescript). Also not sure if Angular's compiler supports CSS compilation.


Looks great. I'm looking forwars to experiment with it. I enjoy that you have taken some of the "it's just js" approach from React, some of the reactivity from Vue/Mobx and the good parts of AngularJS (bindings where it makes sense). I am very curious!


The style of the talk was a bit overly confident to my taste, almost presumptuous.

But the idea of replacing a framework with a compiler blew my mind, so thank you.

And subverting the labeled statement is a wonderful hack. The kind that sticks.

I’m very impressed overall even if a bit scared from the “bad kind of magic” cited.


>> Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you're able to write ambitious applications with excellent performance characteristics.

The best and self-defining para from article


I was giving a chance to Svelte when it was upgrading to version 2 and releasing this compilation thing but it failed badly during a project that I was building due to some bugs of Svelte had with transpiling. Should I give it another chance?


Yes!

(Longer answer: what sort of bugs? Was there an issue on GitHub?)


reminds me a bit of a very old project called FlapJax: https://www.flapjax-lang.org/tutorial/

Elm is a compile to JS language with a small footprint (it does still use a virtual-dom though). It would be nice to see a size comparison of the two. https://elm-lang.org/blog/small-assets-without-the-headache


In case you're reading this, Rich, thank you for choosing the term "compiler" and not "transpiler" when describing what Svelte is!


Very happy for this. I wrote a Firefox extension with Svelte v1, and will take this release of Svelte v3 as an opportunity to refactor my extension.

Thank you, contributors!


Would be interested in learning the size difference. What does your extension do?


This is my extension: https://addons.mozilla.org/en-US/firefox/addon/workspaces-fo...

It's a Sublime Text-inspired navigation tool for Firefox. I use it to jump around between tabs on different workspaces or different monitors. (Yes, I know the default keybinding is bad. I'm going to change that in the post-refactor version.)

My plans are to refactor it for the new Svelte, then improve the fuzzy search, and possibly go cross-browser.


Are there any write-ups about the internals of Svelte? I would be especially interested in how state changes are converted to concrete DOM updates.



Cool, I'll wait! (no pressure :) )


This is a good idea. (Long time Svelte user here.)


So basically mostly the same thing MobX does in React and Vue does out of the box?

That's not a bad thing - that's the "good" kind of Reactivity and how most UI should be written IMO - it involves significantly less boilerplate.


Yes! I talk a bit about prior art in this section of a recent talk: https://youtu.be/AdNJ3fydeao?t=504. (Michel Weststrate, the MobX creator, was in the audience!) The difference in how you end up writing your code when you don't have a `this` turns out to be quite profound, and is the main reason that Svelte components are so concise: https://svelte.dev/blog/write-less-code

It's also worth noting that this approach means there's none of the overhead involved in creating proxies.


Also, thanks for rollup, I've used it today and it was a lot of fun to work with. I was up and running (after experience with webpack) very quickly and everything I needed was well maintained and I was pleasantly surprised!

The main blocker for me adopting Svetle (and opting for Vue and React) is tooling to be honest. I want code that has a lot of visibility, meaningful stack traces and the debugger stopping in relevant places. If Svetle 3 does everything synchronously (like MobX) I'd love to check it out!


Updates are asynchronous (they happen at the end of the event loop, so that `x = 1; y = 2;` results in one update instead of two), but I hear you on tooling. Svelte isn't yet as mature as other frameworks on that front (though debugging isn't bad in my experience). One day soon, hopefully!


I was actually physically close to YGLF but unable to attend, I spoke there at a previous year. Michel is a friend and I collaborated with him on MobX. He's also one of the nicest people I know and he visits often.

I think you might want to check out WPF + PostSharp for something very similar to this approach in C# land. I definitely think it's the right approach for reactivity.


Echoing your comment about Michel — he's a prince among men! Was great to meet him at YGLF


And also, since you don't need Proxies, you can target not so old browsers.

We're working on a project with MobX 5 and mid project we realized some of our users on iOS 9 or KitKat do not have Proxy.


And not just that, there's no framework or runtime running in the page when using Svelte. It's all compile time, unlike React, etc.


Looking at the talk, how is this different from markojs?


For the sake of an example, let's stop "pure, simple" hello world with `let x = 1;`.

Instead, please put some real async stuffs, how to manage state, how to put state into many small components.

Examples, not just documentation matters.


There's an incredibly thorough tutorial with an IDE and examples of all of the things you mentioned plus TONS more. It was super easy to find... https://svelte.dev/tutorial/writable-stores


He did that. Go through the tutorial, it is extensive.


So, how about a React-to-imperative compiler?


Is there a DevTools which allows us to view the tree of components and manipulate it, like Vue does? Is there a script tag mode so it can replace jquery?


> Instead, Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM.

So, Svelte is compiled into web assembly? If not, given the emitted imperative code is less efficient than emitted web assembly and the emitted imperative code is less concise than the original declarative code, then what would be the advantage of an imperative translation of the declarative Javascript code compared to emitted web assembly or the original?


See here for a discussion of WASM https://youtu.be/AdNJ3fydeao?t=1410


Are you mixing up code you write vs the code emitted?

The code you write in Svelte is reactive/declarative, emitted code is regular imperative JS.


Though the idea has been bounced around a few times in the Svelte forums for compiling to web assembly




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: