
Introduction to Svelte - lobo_tuerto
https://daveceddia.com/svelte-intro/
======
playpause
For those confused about the "29 MB": that's the size of the compiler itself.

A compiled Svelte app is _tiny_. Taking the TodoMVC demo app as an example:

React [1] : 289 KiB over the wire (decompresses to 1,255 KiB)

Svelte [2] : 28 KiB over the wire (decompresses to 41 KiB)

\---

[1] [http://todomvc.com/examples/react/](http://todomvc.com/examples/react/)

[2] [https://github.com/sveltejs/svelte-
todomvc](https://github.com/sveltejs/svelte-todomvc)

~~~
acemarke
FWIW, that React demo should not be used as a network perf comparison in any
way:

\- It's using an ancient version of React (0.13.3)

\- It's a debug build of "React with addons", not a minified prod build

\- It appears to include `JSXTransformer.js` as a separate script to handle
in-browser JSX compilation

If you were to redo this using a modern version of React and a standard CRA
build, I guarantee it would be _much_ smaller.

 _edit_

Just for kicks, I did a quick search and dug up a pre-existing React "TodoMVC"
app based on CRA ( [https://github.com/ChrisWiles/React-
todoMVC](https://github.com/ChrisWiles/React-todoMVC) ). It's 3 years old, but
it was trivial to bump the requirements up to the latest versions of React and
react-scripts.

From there, running `yarn build` says that:

    
    
        File sizes after gzip:
        
          39.22 KB  build\static\js\2.3ec0f98b.chunk.js
          2.14 KB   build\static\js\main.4514f0a8.chunk.js
          1.73 KB   build\static\css\2.bc2ff3bb.chunk.css
          782 B     build\static\js\runtime~main.0ff4d30b.js
    

The actual sizes on disk are:

    
    
        2.3ec0f98b.chunk.js : 128435b
        main.4514f0a8.chunk.js: 7259b
        2.bc2ff3bb.chunk.css: 5423b
        runtime~main.0ff4d30b.js: 1577b
    
    

So yeah, Svelte is certainly going to result in much smaller bundles than a
React app, but you have to use a legitimate fair production comparison.

~~~
hajile
Looks like Preact comes in at 6K (compresses to 4.7K). That's pretty
interesting when you realize that Preact generally about as fast or faster
than Svelte in a lot of benchmarks.

[https://github.com/developit/preact-
todomvc](https://github.com/developit/preact-todomvc)

[https://medium.com/@ajmeyghani/javascript-frameworks-
perform...](https://medium.com/@ajmeyghani/javascript-frameworks-performance-
comparison-c566d19ab65b)

That said, I don't know that 6K vs 40K is particularly significant. For small
apps, it disappears into the noise compared to ads, images, video, trackers,
etc. For large apps, the framework starts to make less and less of a total
percentage of the total app and often slides into insignificance on that side
as well.

------
Zelphyr
This looks nice. I'm not a framework guy (more on that in a second) but they
at least seem to be heading in the direction of letting me get work done
without forcing me to do it their way.

That said; first it was Backbone which wasn't terrible but kinda clunky in my
opinion. But then Angular came along and everybody rushed over to that
pasture. But then React came along and everybody rushed over to that pasture.
Now Vue is appearing to be greener than the others. Is Svelte where everyone
will go next?

My point is this: if all these frameworks were so great, why do we keep
running to the latest new one? I actually heard a contractor say the other
day, "five years ago everybody wanted Ember developers and now everybody wants
React developers. I even have those old Ember clients coming back asking for
developers to rewrite the Ember projects in React."

Maybe it really is turtles all the way down...

~~~
hardwaresofton
tl;dr watch this fantastic intro to svelte talk by it's creator:
[https://www.youtube.com/watch?v=AdNJ3fydeao](https://www.youtube.com/watch?v=AdNJ3fydeao)
, it covers some of the growing pains of React that svelte addresses.

While it might _look_ like the frontend is going around in circles, there are
major & minor differences between the technologies, and they have each
introduced novel (to JS at least) things... Off the top of my head (this
timeline might not be right but it's how I went through it at least):

\- Backbone got you away from jquery spaghetti, helped you actually manage
your data & models. Often paired with Marionette to handle views (if you
squint this is the precursor to components) and bring some order in that part
of the app.

\- Angular bundles backbone's data handling (services), marionette's orderly
view separation (views, directives), but they made a fatal mistake in the
apply/digest cycle and maybe encouraging a bit too much complexity. Angular is
_everything_ bundled together, with consistent usage/documentation/semantics,
a familiar programming pattern (MVC), and a large corporate sponsor in Google
it caught on like wildfire.

\- Knockout sees Angular's MVC, laments it's complexity and focuses on MVVM --
simple binding of a model and a relatively simple reactive-where-necessary
controller

\- React comes along and suggests an even simpler world where the _only_ first
class citizen is components and everything else comes separate (this isn't
necessarily new, there is an article out there comparing it to COM subsystems
for windows). React is almost always used with react-router and some flux-
pattern supporting data management lib -- these are also departures from how
angular, backbone and knockout structured in-application communication
(backbone was pure event bus, angular had the usual MVC methods, knockout was
just callbacks -- if you have a handle to an observable when you change it
things reload).

\- Vue sees the complexity that React grew to (case in point:
shouldComponentUpdate) and devises a much simpler subset along with a new way
to handle reactivity -- using the `data` method of a vue component. Vue made a
_lot_ of decisions that helped it stay simple and small yet very productive
and this is in large part thanks to React existing before hand.

\- Svelte comes on the scene and realizes that truly optimal rendering could
be achieved by just _compiling away_ the excess and eschewing the virtual dom
all together in most cases. No need to track all the structure if you compile
the code with the updates necessary. Don't quote me on this but I think a
whole host of things influenced this project -- smarter compilers, better type
systems, the ideas around zero cost abstractions & doing more work at build
time.

\- Ember (formerly SproutCore) is actually an anomaly because it tries it's
best to be both angular like (so large, and usable by large teams) _and_
keeping up with the tech as it evolves (see: Glimmer, Octane). Ember also has
some innovations, like Glimmer's VM-based approach -- turns out you can just
ship binary data representing how to draw your components to the browser and
skip a bunch of JS parsing, if you bring your own virtual machine that is
optimized to draw the components.

As all this moves forward, there are ecosystem pieces like typescript that
have gained tons of steam and changed how people are writing JS code these
days.

~~~
Zelphyr
This is literally the first time anyone has ever put together a cogent
argument for why the framework du jour exists. Thank you!

I still personally feel like I can usually get more done with pure Javascript
but, as I said in my original post, at least they appear to be headed in a
better direction. I did a project in Vue last year and it didn't entirely
suck. Unlike the nightmare that was an Angular project I did two years ago.

~~~
jf22
In an earlier comment, you said you weren't a "framework guy".

If you were you would have heard this cogent argument dozens of times already
as it's fairly common knowledge to people who are into frameworks.

Consider trying to understand why frameworks are created before using them.
Understanding the motivations behind a framework will help you navigate the
api easily and could change your opinion about whatever frustrates you.

~~~
hardwaresofton
I'd also consider myself not a "framework guy" \-- Spring is not my favorite,
I pick flask/sinatra over rails/django, servant over yesod, vue + vue-router
over ember (these days) etc.

Maybe the distinction is that it really matters _which_ framework, and how
it's put together, and how much you have to commit to use any of it.

I think the commenter's question was really more about the diaspora of these
tools and why they all exist -- svelte is pretty decidedly _not_ a framework
(in fact I don't even think you can make it one, AFAIK there isn't like a
"svelte data"). IMO the only full blown frontend frameworks are Ember, Angular
and react/vue + react/vue-router + flux-y pattern data store.

------
nailer
I've been building something with Svelte 3 for about 6 months now.

\- As should be clear in the article, it's _very_ easy to pick up. In the
first couple of weeks I got compiler errors, and kept having to look at how
props and binding worked in the tutorial, but now I just make components
without having to really think about Svelte.

\- TS support is on the way (yaay)

\- I'd like to know more about server-side rendering on Lambda - ie, Sapper
currently wants to use something persistent like Express, but that really
shouldn't be necessary.

~~~
wirahx
Sapper can generate static html for lambda or anything else i f you run `npm
run export`.

In fact the ideal way to use Sapper is without express/polka.

~~~
nailer
Hah brill. It might just be the tutorials, which seem focused on using express
or something with express-like middleware. I'll do some further investigation.
Thanks.

------
gedy
I loved Svelte a few years back and still think it's a nice framework with
cool ideas. However, a big issue for me using it at a company is that testing
(especially unit testing) seems to be an afterthought. This has made it a non-
starter for using it with multiple teams working on same code base. Maybe it's
changed with Svelte 3 but a library I wrote for it wasn't clear how to test.

(Edit sounds same: [https://github.com/sveltejs/svelte/wiki/FAQ#how-do-i-do-
test...](https://github.com/sveltejs/svelte/wiki/FAQ#how-do-i-do-testing-
svelte-apps))

JS libraries sometimes take a non-presciptive approach of "test however you
want!", But roll your own testing for a UI framework really limits adoption
and enthusiasm at larger companies.

~~~
lucisferre
Is there any UI framework where testing isn't an afterthought?

~~~
gedy
React at least had ReactTestUtils 'officially' and then recommended
ReactTestingLibrary & Enzyme as the ecosystem matured:
[https://reactjs.org/docs/test-utils.html](https://reactjs.org/docs/test-
utils.html)

------
dccoolgai
This looks much more germane to the Web than the other frameworks du jour.
Will be interesting to see how it develops, but this was a pretty interesting
look at how it works.

~~~
nailer
Ins't /Svelte/ the framework du jour? :)

~~~
azangru
Doesn't du jour imply that it's the go-to framework of the day? Surely, that
would be React :-)

~~~
nailer
JQuery was a completely different way of looking at things with a huge
advantage. It got popular and became the go-to tool of the day.

Backbone and Angular were a completely different way of looking at things with
a huge advantage. They got popular and became the go-to tool of the day.

React was a completely different way of looking at things with a huge
advantage. It got popular and became the go-to tool of the day.

Svelte is a completely different way of looking at things with a huge
advantage.

------
sktrdie
I like reading scientific papers and most examples sections provide rich and
intricate outlines of real-life use-cases where the idea can be experimented
against. These examples usually involve quite complicated scenarios that "put
the idea to the test".

One that I recently read involved a solution to the "Challenge Problem" [1]
(simulating the movement of a rover) which involves lots of interesting
properties and allows one's idea or framework (or whatever) to really battle
test the grounds with reality.

On the web however it's different... we're somehow stuck with todo-lists.

1\.
[https://mdetools.github.io/mdetools18/challengeproblem.html](https://mdetools.github.io/mdetools18/challengeproblem.html)

~~~
olooney
Todo apps are used as front-end examples for the same reason the factorial
function is used to explain recursion: it's simple, it's intuitive, but it
exercises what you need without dragging in a lot of incidental complexity.

To demo or teach a front-end framework, you need to show:

1\. How data gets rendered to the DOM

2\. How collections are handled

3\. How events are registered and handled

4\. How the DOM is updated when data are changed

5\. How form inputs are represented

The easiest thing to do is to show an array getting rendered as a list, then
add click handlers which change the list somehow, which naturally segues into
showing how the DOM is changed. Adding new items or deleting items also answer
important questions about how exactly collections of data are mapped to
collections of elements and how updates are happened. Finally, no demo of a
front-end framework can be considered complete unless it addresses how form
input elements work; adding functionality to add a new item or update the text
of an existing item is an obvious way to demonstrate this.

~~~
sktrdie
I disagree. Those things are already available in pure library-less and
framework-less code. What frameworks should provide is a solution at scale (i)
as complexity increases, (ii) whether code is more maintainable or not and
(iii) also I guess how easy it is to "fix" as bugs are discovered.

A todo-list gives you pretty much 0 insight into almost any of these facets.
Let's be honest here, it's a "hello world" cheap demo to quickly showcase:
"here's how my new framework works" and you can quickly understand it.

But you have no way of understanding whether those framework decisions
actually work at scale. More complex examples are a good thing, not a bad
thing :)

------
daoxid
The article says that

    
    
        items = items.filter(i => i !== item);
    

is compiled to

    
    
        $$invalidate('items', items = items.filter(i => i !== item));
    

So this invalidates the whole array, right? Would this then re-render the
whole array, i.e., remove and recreate all DOM nodes? And if so, does Svelte
support more fine-grained ways to update arrays?

~~~
hajile
The TL;DR is that Svelte overpromises. They can't possibly write code for
every transformation combination as code size would grow exponentially (I'm
not completely sure, but I think predicting transforms would involve the
halting problem).

(thanks to whoever bothered to do this writeup).

[https://github.com/gactjs/gact/blob/master/docs/long-live-
th...](https://github.com/gactjs/gact/blob/master/docs/long-live-the-virtual-
dom.md)

EDIT: if anyone has proof this is not true, I'd love to hear their
counterargument.

~~~
rich_harris
Svelte author here. That post overlooks a number of important points; I've
responded here
[https://www.reddit.com/r/javascript/comments/ckpdxk/long_liv...](https://www.reddit.com/r/javascript/comments/ckpdxk/long_live_the_virtual_dom/evq8g2k/)

~~~
hajile
React is _very_ far from the fastest vdom. It notably suffers from needing to
work with non-DOM back-ends where a particular heuristic that is good in the
DOM may either be useless or (worse) actively degrade performance. Preact,
Snabbdom, or Inferno would probably be better points of comparison to Svelte's
approach as they are much more optimized for the web.

DOM nodes can actually be recycled relatively easily. Cache the nodes by type
then by class. Most recycled nodes would be a 100% match based on those two
alone. If type and class match, then you have a super-high probability of
dealing with old nodes for the same object, so few modifications are required.
Most nodes without classes tend to have no attributes changed (<div>, <p>,
etc) so they will match as well. Store those nodes with their vdom attached
and you will have a record of what has been modified so patching is fast.

This optimization exists in some vdom implementations and would make the case
in question much faster. There also seems to be an implication that the
diffing algorithm will bloat. If you look at React, the diffing algorithm is a
very small part of the codebase.

This is hardly just an academic optimization though. It is _the_ key to
reducing overhead on long lists. With long lists of complex objects, you
cannot rely on patching text values because there will undoubtedly be actual
DOM differences. Rather than dooming the entire list to poor performance, you
can recycle those nodes and retain most of the performance of a flyweight
scroller where nodes are all identical.

[https://developers.google.com/web/updates/2016/07/infinite-s...](https://developers.google.com/web/updates/2016/07/infinite-
scroller)

~~~
daliusd
Either I have completely misunderstood you or you are simply wrong. It looks
like you are implying that vdom is magical solution to long lists and svelte
should have problem here. While in real world we have this:
[https://svelte.dev/repl/f78ddd84a1a540a9a40512df39ef751b?ver...](https://svelte.dev/repl/f78ddd84a1a540a9a40512df39ef751b?version=3.8.1)

~~~
hajile
Like most other scrollers, the svelte one tries to only show the elements on
screen plus a couple above and below to keep up the illusion. The Google
article makes it very clear that top performance requires re-using DOM nodes.

In that very simplistic example, there are only 4 nodes to each list, so
creating and destroying them doesn't matter. I have a scroller in a business
app where each item has a few hundred DOM nodes. Create and destroy them
constantly and you'll definitely notice on a desktop and performance will
crawl on a mobile device.

Instead, you want to save those DOM nodes in a cache and re-use them. In order
to do this though, you must know what parts are default and what parts have
been modified by their previous user. A vdom does this automatically, but the
cost for Svelte to calculate which of the hundreds of properties have changed
is too big, so they just throw it away and make another.

An even better optimization would be where each list item has the same node
structure and only text or images change. I believe Svelte can handle this
case. Unfortunately a lot of lists are slightly irregular in real-world
applications. I work with these kinds of lists a lot and a vdom keeps it
smoother than all the other libraries we've looked at.

~~~
daliusd
I don't see what stops you adding caching in Svelte for virtual lists.

~~~
hajile
Imagine you add a few attributes, some properties, and a couple event
listeners to a node. In order to reuse the node, you have to reset it to
factory settings.

How would Svelte know what things had been changed when looking at a node
saved in a cache?

If it has to check every property, the cost to check will exceed the cost to
create new. If it saves a list of changes, it's essentially created a vdom
anyway.

~~~
daliusd
Thank you for explaining that to me. It is good to know what technology to use
if I will meet this specific case. So far all projects I have worked on can be
implemented both with React and Svelte :)

------
Doctor_Fegg
> Another nice thing: the node_modules folder for this Hello World Svelte app
> totals only 29MB and 242 packages

"Only".

~~~
nailer
That's the compiler, not the output of the compiler.

Likewise GCC/LLVM is huge, but helloworld.bin is pretty small.

~~~
Cthulhu_
How big is the source code size of GCC/LLVM? I mean node_modules often
contains the full source + dist of the whole dependency chain.

~~~
saagarjha
The source-controlled (and somewhat out of date) folder for LLVM is about a
gigabyte on my machine.

------
Zelphyr
"Another nice thing: the node_modules folder for this Hello World Svelte app
totals only 29MB and 242 packages."

How is it nice that you have almost 30MB of code for something that prints
"Hello World"?

EDIT: For what it's worth, I don't fault Svelte for this necessarily. This is
indicative of NPM bloat which is becoming rampant in my opinion.

~~~
jacobedawson
To be fair, the Svelte bundle.js that you would actually serve to a browser is
only 2.3kb. The 25mb is what the dev's computer has to store in its
node_modules.

"Another nice thing: the node_modules folder for this Hello World Svelte app
totals only 29MB and 242 packages. Compare that to 204MB and 1017 packages for
a fresh Create React App project."

~~~
Zelphyr
A somewhat apples-to-oranges comparison I know but; 277B:

    
    
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <title>Test</title>
        </head>
        <body>
            <div id="howdy"></div>
            <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', () => document.getElementById('howdy').innerHTML = 'Hello world!')
            </script>
        </body>
        </html>

~~~
lioeters
Omitting html, head, and body tags is allowed by HTML specs, and the script
tag's default type is "text/javascript". So it could be further simplified to:

    
    
      <title>Test</title>
      <div id="howdy"></div>
      <script>
      document.addEventListener('DOMContentLoaded',
        () => document.getElementById('howdy').innerHTML = 'Hello world!'
      )
      </script>
    

Edit: formatting

------
writepub
We need someone to take Svelte on a test drive for something more complex than
a to-do list. I'm assuming the results will be favorable to svelte, but please
blog _after_ said exercise. The un-ending list of blogs and tutorials on to-do
lists with svelte are certainly plentiful, repetitive, and not particularly
convincing

~~~
theprotocol
FYI I've selected Svelte for an enterprise project and after using it for some
time, it seems to have some pretty big issues. I would honestly call the
current release a beta version.

In particular, there is a _lot_ of flakiness with reactivity and because
reactive things are magical in Svelte, it's very hard to diagnose and correct
such issues. Reactive code becomes spaghetti fairly quickly once you start
adding logic to prevent it breaking.

Those neat out-of-the-box transitions completely break unmounting/remounting
as would be the case with, say, changing "pages" (using a router). If there's
any transition still going on, the unmount will fail and yet the replacement
component will be mounted, resulting in a frankenpage.

It's also maybe _too_ declarative in the sense that certain things that are
easy to do imperatively require you to coerce Svelte to achieve them. You
sometimes find yourself deliberately trying to fool Svelte into doing an
update.

__

But do I regret choosing it? Not really. All frameworks have flaws. IMHO:
Angular is a convoluted spaghetti of nonstandardness, React has its head on
backwards with JSX, Vue has too many quirks... I'm partial to riot.js which
has just been updated to v4, but I have yet to try the latest version.

------
sveit
Mark Volkmann gave a great talk on Svelte[0].

[0]:
[https://www.youtube.com/watch?v=4_PTdJq-1rA](https://www.youtube.com/watch?v=4_PTdJq-1rA)

------
fiatjaf
Doesn't work with Browserify. Please someone make it work with Browserify!

