DEV Community

Cover image for Why SvelteJS may be the best framework for new web devs
Ben Holmes
Ben Holmes

Posted on • Edited on • Originally published at bholmes.dev

Why SvelteJS may be the best framework for new web devs

Any web dev who's been at it for a few years has likely heard this question every other day.

I'm really interested in learning about web development, but I don't know how to start. Any suggestions?

A decade ago, this would have been an easy answer. Just make an index.html, throw some tags in there, make that header turn red with CSS, and reach for JQuery (or plane ole JavaScript, depending on who you ask) to handle those mouse clicks!

...Oh, how things have changed. Now we're running around with build tools, client side routing, special frameworks with fancy runtime scripts, binding "this" everywhere, template literals, CSS-in-JS... how do we choose what matters most? 🤷‍♀️ We can't start teaching how React uses a virtual DOM if someone doesn't even know what the DOM is!

This has led to countless avenues to start with with varying degrees of "just type this now, and I'll explain later." Some encourage beginners to just learn React or Vue right away to get started with modern practices, while others scream from the mountaintops that beginners should always start with the fundamentals. Truthfully, there are merits to both approaches. The former can get newbies excited with hot reloading and components, running the risk of leaving too much to the unknown, while the latter gets beginners understanding how DOM manipulation works under the hood, while possibly steering people away with the complexities of JS we've since abstracted away.

What we need, then, is a middle ground. A way to get started with the fundamentals while soaking up modern concepts like component-driven development, scoped vs. cascading CSS, templating, declarative functions, etc etc etc.

Enter: Svelte

SvelteJS is a pretty new kid on the block just starting to get some attention. Some may know it as the most popular write-in for the State of JavaScript 2018. For the abridged explanation, Svelte is meant to be the framework that isn't really a framework; it's basically a tool to compile components down at the build step, allowing you to load a single bundle.js on your page to render your app. This means no virtual DOM, no frameworks on top of frameworks, and no framework to load at runtime.

These are pretty big selling points for more experienced developers, but most beginners probably couldn't read that last paragraph without their head exploding. Luckily, it's not this compilation sorcery that makes Svelte so beginner-friendly. It's actually the syntax.

If you've never seen a Svelte component before, here's a really basic example:

<p class="pretty">Here's some markup <strong>written by {name}!</strong></p>

<style>
    /* here's some scoped CSS */
    .pretty {
        color: red;
    }
</style>

<script>
    /* ...and a variable we can access in the markup */
    let name = "Ben";
</script>
Enter fullscreen mode Exit fullscreen mode

Let's unpack this a little. So first off, it's worth noting that all of this can live inside a regular .html file, or a .svelte file if your heart desires. Also, we see some familiar tags reminiscent of framework-less development: <style> and <script>. Sadly, writing styles and JS in these tags is necessary for properly building scoped components, but it allows syntax highlighting to work without extra text editor extensions like CSS-in-JS solutions. Plus, Svelte's build step is smart enough to scope any component-specific styles by default, so you won't have styles bleeding between components.

You'll also see some magic happening with that JavaScript variable called name. This is a shiny new concept for Svelte v3, where any variable in your component's script is accessible from markup. Thus, there's no framework specific syntax to learn for state management, so no Angular $scope, no React this.state, and no Vue data. Instead, we can just use lets everywhere to get assignable state values, cuing re-renders whenever these values change.

This freedom from this jargon means making a component can almost feel like whipping up a CodePen, but without wondering how to connect that declarative JS function you learned to some DOM query selector. Don't worry too much though: Svelte won't mess with callback functions or window listeners, so those fundamentals remain.

The other nice thing about these components is that they're just as import-able as a traditional component. Just import the .html and Svelte knows how to unwrap it 😊

<div>
    <Wizardry />
</div>
<script>
    import Wizardry from './wizardry.html'
</script>
Enter fullscreen mode Exit fullscreen mode

Neat, but hang on a minute...

Some readers may find this concept as mind-blowing as I do, but others probably have their pitchforks ready at the thought of throwing this at beginners. Won't this confuse them about how DOM manipulation really works?

The answer is... maybe. But when someone's just starting out (at least from personal experience), it's okay to accept a little abstraction for the sake of making cool things more quickly.

Also, just as languages like Java and JS have abstracted away pointer management with garbage collection, it feels like most every modern web development tool has abstracted away DOM manipulation, save for more advanced edge cases beginners likely won't need to face. Btw, if you are scratching your head at what pointer management is, I think that kind of proves my point 😛 Thus, rather than forcing beginners to manipulate the DOM or grasping framework-specific state wrappers, why not just let them access variables directly from markup? Now they can learn the basic principles of component state without getting caught in the weeds.

Okay I see your basic example, but Svelte must have some framework-specific weirdness to make everything work

Admittedly, this is true, but it's a lot less than you might think. One Svelte-y syntax is for looping and conditionals for displaying DOM elements. This works a lot like the JSX way of returning elements from a map, but without all the nested brackets beginners (and myself) can easily get lost in. Here's a basic one that generates a list of a elements from an array:

<ul>
    {#each profiles as profile}
    <li>{profile.name}: {profile.role}</li>
    {/each}
</ul>

<script>
    const profiles = [
        {name: 'Wes Bos', role: 'React extraordinaire'},
        {name: 'Chris Coyier', role: 'Father of CodePen'},
        {name: 'Cassidy Williams', role: 'Letting you know it's pi time'}
    ]
</script>
Enter fullscreen mode Exit fullscreen mode

Again, I understand any criticisms about the syntax, but what I love is how easily understood it is. Instead of nesting JavaScript in our HTML, we just say hey, lemme loop over this array and create an element for each one.

There's another Svelte oddity worth mentioning that I'm admittedly not as thrilled about: passing props to components. Yes, it is fully functional and easy to learn, but the syntax is a bit too magical for some people's tastes. To handle props, we simply pass the prop to the component wherever it's imported...

<!-- somewhere.html -->
<Profile coolGuy="Scott Tolinski" /> 
Enter fullscreen mode Exit fullscreen mode

...and get that variable as an exported "let"

<!-- profile.html -->
<p>{coolGuy}</p>
<script>
    export let coolGuy = '';
</script>
Enter fullscreen mode Exit fullscreen mode

I totally understand if some are turned off by abusing "export" like this, but it does at least follow the way beginners should conceptualize modules: we export what we should access outside of the component, and import what we want to show in our component.

I might be able to get past that strange-ness... but how about that build step?

So another criticism about getting beginners started with frameworks is the need to use a package manager. Which means... gasp using the terminal!

Look, I get it, popping that thing open can be intimidating, with its monospace font and that spooky "cd" to jump directories. But to be fair, it's really not a huge hurdle when you only need a single command to get running. Additionally, the integrated terminal within VS Code makes it dead simple to get started with; it even plops you down in your current project directory!

Svelte actually offers a downloadable starting point that's nice outside of the box, but I made my own starter template that just uses the build tool Rollup for live reloading. In fact, the config file is under 30 lines long! For a basic Svelte project, these is all the directories and files you need:

/public
    index.html
/src
   index.html
app.js
rollup.config.js
package.json
Enter fullscreen mode Exit fullscreen mode

Just add a command to run the build step in the package.json and you're all set! You could certainly say that all the extra modules and files other frameworks need aren't a problem if beginners don't touch them, but in my eyes, the less extra stuff for newbies to wonder about, the better.

Okay fine, it's cool and beginner-friendly. But is it a stable framework?

This is a very relevant question for a framework as young as Svelte. All examples I have shown use the syntax of Svelte version 3, which is still in beta as of the time of this writing has a relatively small following compared to framework behemoths like ReactJS and VueJS. So as exciting as it is, I would wait another few months before rushing to teach code workshops with it. Still, Svelte offers a really concise page for documentation for version 3 that can ease beginners into the framework without getting overwhelmed by subpage after subpage of explanation.

So let's go over some of the main selling points for learning web development with Svelte:

  • It's a component-based framework with 0 extra plugins
  • It handles state management without all the usual cruft
  • It uses scoped styling without needing CSS-in-JS (so no editor extensions or wacky syntax)
  • It only needs a dead simple build script to get going
  • Hardly any files are needed in a base project

Of course, it's totally fine if I haven't convinced you with this post; all good posts stoke a little controversy! But I hope it at least showed you how freaking cool and simple Svelte can be to learn.

Learn a little something?

Awesome. In case you missed it, I launched an my "web wizardry" newsletter to explore more knowledge nuggets like this!

This thing tackles the "first principles" of web development. In other words, what are all the janky browser APIs, bent CSS rules, and semi-accessible HTML that make all our web projects tick? If you're looking to go beyond the framework, this one's for you dear web sorcerer 🔮

Subscribe away right here. I promise to always teach and never spam ❤️

Oldest comments (59)

Collapse
 
nickytonline profile image
Nick Taylor

I'd heard about SvelteJS but hadn't really looked into it. So basically everything in one file with regular HTML tags like <style /> and <script />. Seems pretty painless and stuff like the foreach syntax isn't that foreign for anyone whose done Handlebars or Meteor's Spacebars, i.e. #each.

Thanks for the writeup. Looking forward to your next post Ben!

Collapse
 
shirasugyoza profile image
Shirasu

I'm beginner coder who is trying to understand React and Vue but can't get what to start from... I'll try your starter template. Thank you!

Collapse
 
bholmesdev profile image
Ben Holmes

Omg that's awesome, thanks for the interest! Please don't hesitate to reach out to me on Twitter or elsewhere if you get stuck. I tried to make everything clear but learning any new tool can be hard, especially with a newer framework like this 😊

Collapse
 
tailcall profile image
Maria Zaitseva

If I'm not mistaken, Svelte is from the creator of Ractive.js, which I really enjoyed when I was building an app with it. I like how Svelte pushes some of sweet Ractive's ideas to the limit – Ractive compiled templates to functions, so re-renders get pretty lightweight, and Svelte compiles the whole source file into a frameworkless script. A nice feat, I think! This is how I'd like web frameworks to be.

Collapse
 
paulmaly profile image
PaulMaly • Edited

Yea, Ractive was great, but too underestimated (( I hope Svelte will become more popular. Btw, maybe you would like to join us to Telegram channel: t.me/sveltejs

Collapse
 
katafrakt profile image
Paweł Świątkowski

IMO Ractive hit a really bad timing. Just when it started to get some attention, React was announced and of course people went for something from Facebook.
Another underestimated framework was MithrilJS.

Collapse
 
nbeers22 profile image
Nate Beers

Reminds me a lot of Vue. I'm curious as to the advantages this might have over just using Vue. Not having to put something within a data property isn't really much of an advantage, so there must be something else, no?

Collapse
 
thatjoemoore profile image
Joseph Moore

From the article:

For the abridged explanation, Svelte is meant to be the framework that isn't really a framework; it's basically a tool to compile components down at the build step, allowing you to load a single bundle.js on your page to render your app. This means no virtual DOM, no frameworks on top of frameworks, and no framework to load at runtime.

That's the big difference with Svelte - it exists only at build time, outputting self-contained components with no runtime library to load. The ideas behind it are spelled out by the creator in this talk:

The combination of simplicity and small runtime size/sheer speed is what has attracted me to Svelte, and the upcoming V3 looks to improve even more on both fronts.

Collapse
 
paulmaly profile image
PaulMaly • Edited

Seems Vue should remind you Ractive a lot. Svelte is the next step from the best Ractive's ideas to most modern approaches. Vue would always be only the catching-up imitator.

Collapse
 
revskill10 profile image
Truong Hoang Dung • Edited

Seriously, React Suspense for data fetching , plus React Hooks for business logic are gonna throw other frameworks out of water.

Collapse
 
rafistrauss profile image
rafistrauss

That's kinda the point of svelte - it's not a framework (in the sense that it's all compiled to vanilla JavaScript and there's no additional overhead).

I'm a huge fan of the concepts of svelte for that reason, so while React is certainly the heavy hitter at the moment, I'm hopeful the trend moves more where svelte is heading

Collapse
 
paulmaly profile image
PaulMaly • Edited

Seriously? React Suspense + React Hooks will inflate fatty React even more. No thanks!

Collapse
 
antony profile image
Antony Jones

React Hooks is what Svelte 3 is inspired from, so your comment already shows a distinct lack of knowledge and ignorance towards the subject matter.

Having said that, Suspense looks interesting and there isn't a way to replicate the exact same sort of thing in Svelte right now.

However, framework choice is about trade-offs, and right now, React has far more impactful trade-offs when compared to Svelte or Vue. I don't think anything is getting blown out of the water just yet.

Collapse
 
mateiadrielrafael profile image
Matei Adriel • Edited

What do you mean by Suspense looks interesting and there isn't a way to replicate the exact same sort of thing in Svelte right now.

In Svelte we have the #await block :)

Collapse
 
lithmage profile image
LithStud • Edited

And i still say - make index.html toss in some tags add in css and then some vanilla JS. Nobody should start with build tools, libs and all the rest stuff. Once you learn basics then go with what is need for project (maybe angular, maybe vue, whatever is needed).

Collapse
 
amiangie profile image
am i angie?

This. Please, lets start with semantic HTML and well-written styles.

Collapse
 
mrgnw profile image
Morgan

For new people, the interactive tutorials and live playground (repl) are very helpful!

(Both links are v3, which is nearing release)

Collapse
 
raguay profile image
Richard Guay

I'm creating a project, mostly for my own use. I first wrote it in Vue.js, then moved it to Mint, and not I have it on Svelte v3. The Svelte version is the easiest to maintain and expand. But it also respond the fastest to UI changes. Since it is a desktop application using nw.js, the speed is much appriciated. People understand UI delays on a web page, but not for a desktop application.

Collapse
 
matthewk007 profile image
Hey Wow. Oh Wow. • Edited

not a new dev, but as a server-focused dev Svelete is useful for 2 primary reasons:

  1. no npm madness
  2. fetch into {#await} (React et all requires a class and three functions for this ubiquitous promise-based networking)

The second point: Built in template reactivity, is comparable to Go's build-in concurrency. Game changer that future frameworks can't do without.

Collapse
 
katafrakt profile image
Paweł Świątkowski

Wow. I remember stumbling upon Svelte long time ago and it seemed a bit like a toy then. Looks like it developed nicely. I'd like to give it a try in near future.