iJS CONFERENCE Blog

Getting Started with Svelte

Feb 18, 2020

Are you curious to know what Svelte is? Do you know why it’s becoming a popular JavaScript compiler? In this article, we will tackle what Svelte is, who made it, why would you want to use it, its ecosystem, and current state.

Ten years ago, the traditional concept of web development was page-oriented. When you built a website or an application, you would think in terms of the pages – how many pages you need, how they should relate to each other, etc.

Every single page may have its own JS and CSS dependencies, or global dependencies, depending on features and functionality.

So, finally, the page may end up with something like the image above. This solution is hard to scale because loading too many scripts can cause a network bottleneck. The second option is to use a big JavaScript file containing all your project code, but this leads to problems in scope, size, readability, and maintainability.


Image credit: Andrew Pishchulin

When you need to deploy the app, you have to copy all of the HTML, JS, and CSS files to a production environment, which might be dozens or even hundreds of files.

Lastly, to host all of your application files, you need a server, which can manage the folders structure, handle routes, and so on.

Now, we are in a component-based web development era.


Image credit: derickbailey

As you can see in the image above, each component is a piece of UI. We can build these components in isolation and put them together to build complex UIs.

Some benefits are:

  • Allows for code re-use
  • Increases your ability to change the software to meet new requirements
  • Ensures UX consistency across a portfolio
  • State-driven

Then, package the application with the help of bundlers such as:

  • Webpack
  • Parcel
  • Fusebox
  • Rollup


Image credit: Andrew Pishchulin
Those bundles are included out of the box in JavaScript frameworks like Angular, Ember.js, Vue.js, and React.js through the CRA bootstrapper. What’s common among these frameworks is that the bulk of the work is in the browser.

A few years ago at a Brooklyn meetup, Jed Schmidt explained his vision of a next-generation UI framework. He said, “The apps we write are directed graphs, but the runtime we have is a tree, the DOM. So, writing an app should be just writing a graph, and the compiler would figure out where the dipoles are and rig up the DOM event code to make that relationship consistent across states.”

There was this smart guy, Rich Harris, listening to Jed. Suddenly, he had an epiphany: “Frameworks are not tools for organizing your code, they are tools for organizing your mind.” Rich Harris says that frameworks help you write better code, but their true value is in the way they help structure your code and express it. Well, I agree with that. So, what if a framework wasn’t a thing that runs in a browser at all? What if it was a compiler?

Now let’s get to the meat of the topic, but first, let’s answer the question: What is Svelte?

  • An alternative to web frameworks such as Vue, Angular, and React
  • A web application compiler, not a runtime library
  • Does not use a virtual DOM
  • Written by Rich Harris at The New York Times in late 2016

Svelte takes inspiration from reactive programming in the way it runs code. But first, let me step back and ask you, what is reactive programming? You can read the definition of reactive programming here on Wikipedia: https://en.wikipedia.org/wiki/Reactive_programming.To make it short, reactive programming has key similarities with the observer pattern commonly used in OOP.


Image credit: developers-club

I’m assuming you have encountered pub/sub design pattern at some point. To differentiate the observer pattern from publish/subscribe: observers are aware of the subject. Also, the subject maintains a record of the observers. Whereas, in publisher/subscriber, they don’t need to know each other.

Here’s a spreadsheet.

When you make a change in a cell, all the cells that depend on it, change too. This makes the spreadsheet so intuitive. This is what Svelte does by default; it brings reactivity to JavaScript itself.

Now let’s see how Svelte works.

You can write regular JavaScript code, but you need to follow a specific syntax.

When you run the Svelte compiler over your code, it compiles that code to optimized-runtime instructions. You are probably saying right now, “Is that important?” Yes, pre-compilation can significantly lower a framework’s overhead.

Take a look at this. Svelte did away with this typical scenario because apparently there’s a performance penalty with frameworks that don’t pre-compile. This is due to compilation/translation that happens on the client side before any of the actual app’s code can be run.


Image credit: Evan You

Let’s review how Angular, React, and Vue detect changes in their app state. Here’s Angular’s dirty checking.


Image credit: Evan You

Here’s React’s reconciliation.


Image credit: Evan You

And here’s Vue using both change detection principles of Angular and React.

Svelte changes detection differently. Its component code will be compiled into vanilla JavaScript with code detection already in place. This is almost exactly the update code that Svelte generates.

Unlike traditional UI frameworks, Svelte is a compiler that knows at build time how things could change in your app, rather than waiting to do the work at run time.

Pre-compilation and avoiding virtual DOM are what make Svelte performant when it comes to memory allocation.


http://krausest.github.io/js-framework-benchmark/current.html

Here’s a js-framework-benchmark screenshot I took last year. Svelte is the first green column, followed by Vue, React, and Angular. This table here shows that Svelte is the winner among the 4 JS frameworks, but take it with a grain of salt. Sometimes these kinds of benchmarks have implementation inaccuracies due to environment modes, not applying framework-specific optimizations, or unintentional errors.

So, let’s go back to how Svelte works. Now, you only ship the code your app needs.

Let me show you how small Svelte can be in comparison with other frameworks.

Here’s Conduit’s RealWorld’s example apps repo.

The smaller the file, the faster the download, and less to parse.

For more info, you can go to this link: https://www.freecodecamp.org/news/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075/ .

So yes. Svelte can produce extremely lightweight code.

But why should you care? You should care because:

  • It can be extremely fast
  • It uses very little memory
  • It can be used on embedded devices, which you’ll see in a bit

In Addy Osmani’s presentation, he talks about keeping your JavaScript bundles small, especially for mobile devices.

Why? Because small bundles improve download speeds, lower memory usage, and reduce CPU costs.

On mobile, you’ll want to ship much less, mainly because of network speeds, but also to keep plain memory usage low.

He also mentioned that JavaScript execution time is important for phones with slow CPUs. And due to differences in CPU, GPU, thermal throttling, there are huge disparities between the performance of high-end and low-end phones.


This matters for the performance of JavaScript, as execution is CPU-bound.

Let’s go back. Therefore, in the browser, that compiled code executes and then renders the user interface.

Shifting the load to compile step can also be seen in other frameworks nowadays. A good example of that is Stencil of Ionic and Solid.js by Ryan Carniato.

To get started, you need a Node.js runtime from nodejs.org and to run the following command.

You’ll see this if you go to your localhost:5000:

But there’s an easier way to try building Svelte components. You can go to Svelte’s official website then go the example tabs.

Here’s how you can easily write a component.

The component structure is similar to Vue’s HTML-based template syntax. There are three parts: the script, markdown, and style. All of them can be arranged anywhere you want.

Here’s how you would create another component to nest it and share it with another component:


Here’s how you write an if-else flow:

Here’s how you would write a for-each loop to render a list:

One-way or two-way data binding is just a few lines of code:

Since Svelte is a compiler, built-in animation, transition, and easing does not add up to the total file size of the app if they are not in use. This is not the case in component-based libraries.

A built-in store API for complex state management:

There’s a lot more, such as reactive statements, class directive, component composition, etc.
Now let’s go to the real world.

Svelte is used for POS systems in Brazil. Roughly 200,000 POS devices are currently in the cities of Brazil. The device runs a very outdated WebKit on extremely memory-constraint hardware. They tried roughly a dozen different kinds of frameworks. None of them could be used because when you press a button, it responded half a second later. Of course, users would be more likely to press it twice and may end up overcharging the customer. But when they tried Svelte, it worked smoothly.

Mustlab is an IT company in Russia that uses Svelte to build applications for Smart TVs.

As you notice here, POS machines and Smart TVs are low powered devices. This is a trend that is only going to increase.


Image credit: Rich Harries

The new frontier is the embedded web, wearables, the Internet of Things, in-car entertainment systems, and smart home control panels. All of these things have displays, so they need UIs and a lot of the time, those interfaces will be built on the web.

What about SSR for SEO? Svelte has Sapper, similar to Next.js of React and Nuxt.js of Vue.

SSR can speed up the first render of your app and improve its SEO.

For blogging using headless CMS, Sanity has a Sapper template.

A headless CMS is a content management system that provides a way to author content, but instead of web-page-rendering, like your traditional WordPress, it provides the content as data over an API.

In mobile development, there’s Svelte-Native. It works on top of NativeScript.


This project is not an officially supported product of either the NativeScript or Svelte projects yet. So let’s see next year.

You can also use Svelte to build WebGL apps.

svelte-gl is still experimental, which means the API is sure to change in substantial ways.

Other things that are good to know:

How do you write tests in Svelte?

Svelte’s testing library for writing tests is available here: testing-library.com/docs/svelte-testing-library/intro.

You can also talk to Svelte developers from around the world through Svelte’s Discord channel. Svelte.dev/chat

If you have questions about Rollup configuration, you can go to their Gitter channel which is gitter.im/rollup/rollup .

Visit sveltejobs.dev to find Svelte jobs.

So, let’s weigh in the bad parts and the selling points of Svelte.

Bad parts:

  • TypeScript is not supported ‘yet’
  • Small community
  • Few third-party libraries
  • Lack of DevTools
  • No big company backing
  • Very few jobs are available out there

But you know what? Angular, React, and Vue had a similar history before. It’s just a matter of time. You can start introducing Svelte to your boss or managers.

These are the points you need to enumerate when talking to them.

Selling points:

  • Easy to pick up
  • Better performance
  • Write less code
  • Extremely small bundles
  • Reactive out of the box
  • Declarative transitioning and animation
  • Best for low-powered devices

So that’s the 10,000-foot view of Svelte. Before I finish up this post, there’s a video on YouTube by Rich Harris titled “Rethinking Reactivity,” where he also explains why Svelte is so good.

Thank you for reading. Peace out!

References:

  • https://svelte.dev
  • https://sapper.svelte.dev
  • https://svelte-native.technology/tutorial

Sign up for the iJS newsletter and stay tuned to the latest JavaScript news!

 

BEHIND THE TRACKS OF iJS

JavaScript Practices & Tools

DevOps, Testing, Performance, Toolchain & SEO

Angular

Best-Practises with Angular

General Web Development

Broader web development topics

Node.js

All about Node.js

React

From Basic concepts to unidirectional data flows