loading...
Cover image for Svelte is the most beautiful web framework I've ever seen

Svelte is the most beautiful web framework I've ever seen

jesseskinner profile image Jesse Skinner Originally published at codingwithjesse.com Updated on ・2 min read

I first heard about Svelte a year ago, when Rich Harris presented it at JSConf EU 2018. The demo gods were a bit harsh on him, but it didn't matter to me, because I was so impressed by his philosophy and ideas that I was already sold. I knew he'd work out the kinks, go through a few major versions, and Svelte would be mature enough in no time.

I kind of forgot about Svelte after that, that was until last week when I read Rich Harris' blog post Why I don't use web components. It reminded how simple and beautiful Svelte's syntax is, and I decided it was time to give it some serious consideration.

First, I played a little bit with the Svelte REPL, and got a sense for how it works. Then I decided to try building a Tic Tac Toe game live on Twitch and YouTube. Even though I'm a total noob when it comes to Svelte, and I'd barely read the docs, it only took me about half an hour to get a Tic Tac Toe game working. After that, I explored some different Svelte features, tried to move the game state into a non-Svelte module, and discovered a few anti-patterns in the process.

At the end, I was completely blown away when I discovered that the production build had only 2,418 bytes of JavaScript..! That's 2.4kb including the Svelte runtime!!!

How does Svelte do it? Because Svelte is a compiler. It only includes the bare minimum of JavaScript necessary to get the job done. It turns the HTML templates you write into extremely simple DOM scripting. It transpiles the JavaScript you write so that your simple variable assignments trigger a re-render. It generates JavaScript classes to represent your .svelte files and wires everything up for you, so the only boilerplate you really need is a <script> tag and a <style> tag.

If you're interested in seeing the Tic Tac Toe game I built, you can clone it on GitHub, and spin it up with npm install, and npm start.

Otherwise, I highly recommend you check out the official Svelte Tutorial and try it out for yourself!


Interested in Svelte and web development? Subscribe to the Coding with Jesse newsletter!

Discussion

pic
Editor guide
Collapse
jaxxeh profile image
Jaxxeh

Been toying with it the past few days, it's brilliantly put together and it really feels like the natural evolutionary step from React/Vue/Angular. And such a small footprint!

Svelte/Sapper + TailwindCSS + GraphQL, we're getting pretty close to Dev Nirvana here! 😎✨

Collapse
philippm profile image
Philipp Mildenberger

To complement the other question about Tailwind:

What are you using to integrate GraphQL, how well does it integrate (I guess Apollo-Client?)?

Collapse
jaxxeh profile image
Jaxxeh

I haven't tested GraphQL on Svelte yet, but yes, I would use Apollo. There is a 'svelte-apollo' package on npm that seems to be quite functional, the README has a few examples, including a Sapper/SSR one.

Having previously used Apollo in a NextJS project, I know how tricky it can be to integrate Apollo with an SSR framework and I don't really expect any different with Svelte. Hopefully I can find the time to play around with it soon! ;)

Collapse
opensas profile image
opensas

what do you use to integrate svelte with Tailwind? I see there are a couple of templates but I'd like to know one that works flawlessly

Collapse
jaxxeh profile image
Jaxxeh

I came across this interesting article a few days ago, and it worked as intended after I went through all the steps.

The author of the article put together a template here if you don't want to go through the hassle of manually replicating the steps from the article, though I haven't tried it myself.

Collapse
jaxxeh profile image
Jaxxeh

Follow-up to my previous comment about Svelte + Tailwind: If you're looking to use Tailwind with Sapper, this template works really well.

Collapse
mattwaler profile image
Matt Waler

If you're using vanilla Svelte with Rollup, it's as easy as installing the PostCSS plugin for rollup and setting extract = true! I have a repo here: github.com/mattwaler/svelte-starter

Collapse
mindplay profile image
Rasmus Schultz

It is a very elegant framework.

The main thing keeping me away is the lack of support for TypeScript. I hear they're working on that though.

In the mean time, the net footprint of a bundle with Preact is comparable in size. I know there's a performance difference, but it's not relevant to most everyday applications - I've never had to do real time animations or anything like that, and Preact performs just fine for anything else.

Svelte is always on my radar though. When they sort out type safety, I will definitely take another close look :-)

Collapse
jesseskinner profile image
Jesse Skinner Author

I love Preact too, but Svelte has me even more excited. I don't use Typescript but I understand where you're coming from. One of my viewers suggested checking out github.com/Axelen123/svelte-ts-tem... which might help you?

Collapse
cubiclebuddha profile image
Cubicle Buddha

Yea, it’s basically a non-starter for me until it gains TypeScript support (which I can’t imagine coming anytime soon unless TypeScript itself starts supporting .svelte files or some kind of HTMLSX file).

Collapse
stevealee profile image
SteveALee

Well given TS will perform Type inference and checking on JS (esp good in VSCode) it kinda does have TS support :) but I know what you mean. You could always create some typings.

Thread Thread
cubiclebuddha profile image
Cubicle Buddha

Creating typings is a whole lot of work when the creators of Svelte could have provided native TypeScript functionality. I mean it’s rather strange since Svelte itself is written in TS. But these are the negatives of the approaching you’re recommending:

  • manually created typings often fall out of sync with the code. So the consumers of your components have code they think is working but it doesn’t actually work.
  • JS-check only checks each file independently of each other (I believe), so you don’t get awareness of the type relationships between your entire app
  • JS-check in an HTML file currently loses a lot of the power you get from TSX because you TSX will tell you if you’ve wired up your HTML properly. As where in Svelte and Vue you don’t have a CLI that will tell you that while your script section is correct... you forgot to pass any props to the Svelte component.

So refactoring becomes challenging because you don’t have he machine to tell you when your modification of the code impacts other code. This ultimately leads to the feeling that you shouldn’t ever refactor because it couple break too many things.

Compare that to working in React + TypeScript. I can refactor anything I want and have confidence that the entire website will still work. I don’t have to worry that renaming a variable in one file will break a distantly related page of the site. It’s that type relationship between pages that Svelte is missing.

Thread Thread
stevealee profile image
SteveALee

Sorry, I dropped the Smiley from my reply :( Typing are definitely a hack, and a 3rd party one at that. I've often hit the sync thing myself.

I agree that if Svelte is itself Written in TS then wit hsome attndtion to details it should provide 1st class TS support. I wonder what the issues are?

I've not used TSX but from what you say it adds a level of utility (I assume as it compiles down to TS, jike JSX does to JS).

Thread Thread
cubiclebuddha profile image
Cubicle Buddha

Yup, TSX is super helpful.

Let's say you have loginComponent.tsx that defines the following component:

export const LoginButton = (props: {userId: string}): JSX.Element => {
   // ... do something with props.userId and then load the page
};

You can then have a main component (typically called App.tsx) like this:

<section>
    Hello! Welcome! Click this button to Login
    <LoginButton userId={userId} />
</section>

And if you forgot to pass userId in App.tsx then the compiler would let you know that you made a mistake. If someone later refactors LoginButton to add another mandatory property, then the compiler will let you know that you forgot to circle back to App.tsx.

Thread Thread
stevealee profile image
SteveALee

Nice. Better to use the language than the react specifc prop checks IMHO

Collapse
mistlog profile image
mistlog

For typescript support, you may find this helpful: medium.com/@mistlog/svelte-with-ty...

Collapse
karataev profile image
Eugene Karataev

I know nothing about Svelte, so two noob questions.

  1. Svelte syntax looks like Vue (no revolution here). If I get it right, the main benefit of using Svelte is the bundle size. Compiler does some magic in the build step and less JS code is provided to a user. It means faster loading, parsing and execution. Are there any other benefits except bundle size?

  2. "Cybernetically enhanced web apps". What does it mean? 🤔

Collapse
jaxxeh profile image
Jaxxeh

In addition to what Jesse said, Svelte compiles to Vanilla JS and does not use the Shadow DOM. All the code is compiled and optimized to work directly on the actual (or 'light') DOM.

I also like the fact that you're using actual CSS in your Svelte components, and the compiler namespaces your CSS. You can also set it up to use various existing CSS frameworks (Tailwind, Bootstrap, Emotion, etc.) as well as PostCSS, PurgeCSS, etc.

Finally, using stores and events, communication and data-flow across components is very flexible and quite easy to use.

Collapse
karataev profile image
Eugene Karataev

Thanks for the addition, my interest to Svelte grows up with every positive feedback.
I just didn't get the Shadow DOM sentence. Did you mean virtual DOM?

Thread Thread
jaxxeh profile image
Jaxxeh

Sorry, yes, that's exactly what I meant. And you're welcome!

Collapse
slidenerd profile image
slidenerd

very stupid question but I had to ask, why wasnt working with the actual DOM done in Vue Angular or React? why only now with Svelte

Thread Thread
jesseskinner profile image
Jesse Skinner Author

Ultimately all the frameworks use the actual DOM, but React, Vue and (I think) Angular use what's called a "virtual DOM" to compare before vs after to see what needs to be changed on the page. Svelte doesn't need that, it compiles to just the DOM scripting needed without the overhead of a virtual DOM.

Collapse
jesseskinner profile image
Jesse Skinner Author

I'm a noob too, and I've never used Vue, but my understanding is:

  1. Yes it's very similar to Vue in syntax, but to be honest I never liked Vue's boilerplate and template syntax. Svelte uses a different template syntax that reminds me of Mustache. And in Svelte, you just use local variables instead of needing to use new Vue boilerplate to define your props and methods. Even if Svelte wasn't compiled, I would prefer it to Vue.

  2. They have a blog post explaining this:

    Svelte has many aspects — outstanding performance, small bundles, accessibility, built-in style encapsulation, declarative transitions, ease of use, the fact that it's a compiler, etc — that focusing on any one of them feels like an injustice to the others. 'Cybernetically enhanced' is designed to instead evoke Svelte's overarching philosophy that our tools should work as intelligent extensions of ourselves — hopefully with a retro, William Gibson-esque twist.

Collapse
karataev profile image
Eugene Karataev

Thanks for the answer, it's much clearer now.
I guess I need to read William Gibson books or re-watch Johnny Mnemonic movie to feel the atmosphere of Svelte 😂

Collapse
mastersvelte profile image
Svelte master

What really drew me to Svelte was the smaller code base. It takes less code to write the same app.

You can see in this article: freecodecamp.org/news/a-real-world...

And I made a video about it too: youtube.com/watch?v=rMBusx68ujY&t=4s

Collapse
jesseskinner profile image
Jesse Skinner Author

I love that too. Migrating from another framework mostly involves deleting code, and that feels great.

Collapse
vladejs profile image
Vladimir López Salvador

Are you using svelte 2? Svelte 3 got out last month and it doesn't looks like Vue anymore.

It got a completely revolutionary way of building UI. It brings reactivity to JavaScript itself

Collapse
karataev profile image
Eugene Karataev

I tried the official tutorial and having full component definition (template, styles and logic) in one file reminded me Vue a lot.

Collapse
adityapadwal profile image
Aditya Padwal

Damn! Such a good thing Svelte is. I have recently started climbing the VueJS ladder and met Svelte in between. I am confused now.

Svelte can be a good alternative for the developers who still prefer vanilla javascript and do not like JS frameworks.

Collapse
condensedbrain profile image
Michael Robinson

I first heard about it from someone who used it for an alternative interface for Mastodon: nolanlawson.com/2018/04/09/introdu...

Maybe I'll take a look and try to make something with it.

Collapse
jesseskinner profile image
Jesse Skinner Author

That's really cool, thanks for sharing!

Collapse
vekzdran profile image
Vedran Mandić

Cool writeup, thanks!! Gave the interactive docs a go a couple of months ago, really neat and catchy stuff indeed. I mostly use React, seen a bit of vue and ng, and what I most like is the verbose and clean JavaScript and I guess good (fast and fun) learning curve(?). The mustaschy template style is not a minus, I can go with it. Will give a go to your live coding sess. Would you mind making a comparison to Ionic's latest Stencil One? Ref: ionicframework.com/blog/introducin... It is a compiler thing also, where in the post they manage to get even smaller bundle size than the amazing Svelte. Crazy times to be alive.

Collapse
jesseskinner profile image
Jesse Skinner Author

Thanks! I actually took a first look at Stencil last week, before I checked out Svelte. I like a lot of things about it, but I'm not a fan of using decorators and classes. Svelte, on the other hand, has so little boilerplate it boggles the mind.

Collapse
nielsbosma profile image
Niels Bosma

I can only agree! We just released our new website filestar.com. When planning this website I found your article and we decided to try Svelte and Sapper and we haven't regretted this a bit. That for helping us to this path.

Collapse
jesseskinner profile image
Jesse Skinner Author

Nice! I'm glad I could help.

Collapse
stevematdavies profile image
Stephen Matthew Davies

Despite being a long time developer, I heard mutterings about Svelte a while back but dismissed them as just mere gossip about, just another Web framework. However, lately I had time to give it a go, and I was seriously impressed. A Compiler, a raw js approach with self scoped styling as automatic AND built in state store ability, what witchery was this. My investigations continue,ans I continue to be impressed. Every dev who's worth thier salt in front end work, should at least, take a good look at Svelte!

Collapse
jesseskinner profile image
Jesse Skinner Author

I totally agree. I think the last few years made developers very skeptical of new frameworks. But the good ideas in Svelte are sooo good that people are starting to notice!

Collapse
dukeofetiquette profile image
Adam DuQuette

From Svelte docs: "You can use reserved words as prop names."

Can you provide an example of when you would want to use a reserved word as a prop name? Or when it would be unavoidable?

I've never had issues avoiding reserved words for a variable name, so I'm intrigued by this particular feature. Thanks!

Collapse
pulljosh profile image
Josh Pullen

React forces you to write <div className="asdf" /> as opposed to <div class="asdf" /> and <label htmlFor="asdf" /> instead of <label for="asdf" />. This is because class and for both have intrinsic meaning in Javascript, and when JSX was first created they were worried that reusing this naming could cause problems. (My understanding is that they now believe that class and for would have been fine in the first place...)

I'm pretty sure that bit in the Svelte docs is saying that those renamings aren't necessary in Svelte.

Collapse
jesseskinner profile image
Jesse Skinner Author

You're asking the newest user of Svelte so I'm really not sure. Maybe someone else has an example?

Collapse
eldarshamukhamedov profile image
Eldar Shamukhamedov

Hmm, maybe this is about class vs className?

Collapse
markel profile image
Markel F.

Looks an interesting library, okay, compiler (don't beat me 😅)

Collapse
perlatsp profile image
Perlat Kociaj

Ahhh Svelte..!
It’s been on my mind to have a look at Svelte,i will definitely play with it this weekend.
Thank you for reminding it to me Jesse

Collapse
xowap profile image
Rémy 🤖

Looks like Vue 0.12 to me.

Collapse
keserwan profile image
keserwan

I should give it a try soon. Looks promising

Collapse
mattwaler profile image
Matt Waler

Couldn't agree more. It's the perfect framework for sprinkling in to an SSR project, and even better if you can do a full CSR application!

Collapse
js2me profile image
Sergey S. Volkov

Currently I'm working on migrate my utility from vanilla to svelte. Svelte components looks fantastic but eslint (+ format plugins like prettier) is not fully supported with Svelte.

Collapse
manifeststefany profile image
MRG.NYC

Thanks! I'm late to the Svelte game. This post is just what I needed to answer some questions about making a move.
Be well.

Collapse
stokry profile image
Stokry

I agree with you completely.

Collapse
maurogarcia_19 profile image
Mauro Garcia

Thanks for this article Jesse!! Svelte looks amazing and I can't wait to start using it.

Collapse
jesperbylund profile image
JesperBylund

Agreed. It's another leap in js frameworks. I'd be surprised if react doesn't follow suit!

Collapse
adityapadwal profile image
Aditya Padwal

Nice Post Jesse.

I invite you to join the Svelte Developers Worldwide group. Would be great to have you in.

linkedin.com/groups/10473500/

Collapse
mastersvelte profile image
Svelte master

I totally agree. I've been making video tutorials here if anyone is interested: youtube.com/channel/UCg6SQd5jnWo5Y...