Bruno Haetinger

Svelte hello world with steroids

August 20, 2020

What is it?

Svelte is a component framework that uses a “imperative” code that updates the DOM directly.

Performance

Svelte is extremely fast! I know that some frameworks have the called “live-reload”, that is the feature where you modify the code and soon the changes will be reflected in the development server. Svelte has the same… or I would call it “live-reloaded” as it is faster than blinking your eyes hahahah. Of course, great part of this power comes from the fact that it uses non-transpiled code and pure Javascript.

Another point is that Svelte doesn’t use Virtual DOM to propagate changes, but it applies them to the real DOM. As you could see here in this article one of the problems with virtual DOM is the diff it has to do against the real DOM to check what to modify. There are more reasons described there that would argue in favor of the Svelte’s performance strategy.

Ease of learning

It’s is interesting to notice is that Svelte components arrange seens to be pretty natural to me. It’s very close to web components. The idea is to declare your component, it’s style inside and it’s business logic in the same file with .svelte type. (kind of HTML + CSS + JS)

Who uses Svelte

As Svelte isn’t so popular, yet, it’s not so easy to see companies using it.As far as I found StoneCo not only use it in production in card machine as they had open positions for Svelte developers. You can find a list of companies that use it in production HERE.

Hands-on

As a first Svelte training, let’s create a super Svelte stepper to hold a number for us.

Steps:

  1. Template clone

  2. Hello World - See it running

    1. Run yarn install to download the dependencies;
    2. Run yarn dev to see the template running;
    3. Open http://localhost:5000 in your browser;
    4. Modify the name prop in src/main.js with any string and take another look in the browser… Voilà!
  3. First Component

    1. Create component

      • Create a new file, inside /src, called Stepper.svelte (you could copy App.svelte.

        Note that there are 3 “sections”:

        <!-- JavaScript code -->
        <script></script>
        <!-- CSS code -->
        <style></style>  
        <!-- HTML (template) elements code -->
        <main></main> 
    2. Inside the <script> let create a variable: export let value; Yeah, it’s weird, but as we are going to receive it as a prop, we should use export. Also, declare a variable inside App component: let stepperValue = 0;

    3. Inside the <main> tag let put some elements to see and manipulate this variable:

      <button>-</button><h1>{value}</h1><button>+</button>

      Now let’s import this component inside App - <script>:

      import Stepper from './Stepper.svelte';

      And use it, placing inside <main>

      <Stepper value={stepperValue}></Stepper>

      The value prop will receive the stepperValue value from App.

      Just to make it a little bit better, you could place these styles inside the Stepper’s <style> tag:

      main {
      	display: flex;
      	justify-content: center;
      	align-items: center
      }
      
      button {
      	border: 1px gray solid;
      	height: 40px;
      	width: 40px;
      	border-radius: 25%;
      	font-weight: bolder;
      	margin: 5px;
      }
      

      Great! Now we can see our very useful stepper. The next step is make it functional and change the value number.

      Before modifying the number, we are going to define the function that will dispatch the change event. To do this, we’ll use the createEventDispatcher function from svelte package and create our custom event:

      import { createEventDispatcher } from 'svelte';
      const dispatch = createEventDispatcher();
      const handleClick = (btnValue)=>{
      	dispatch('btnValue', {
      		value: btnValue
      	});
      }

      So, to see the reactivity of Svelte in action, set the event handler “on:click” inside the buttons element. :

      <button on:click={() => handleClick('-')}>-</button>
      <h1>{value}</h1>
      <button on:click={() => handleClick('+')}>+</button>

      Now, it’s time to create a function to handle the stepper event and add or subtract depending on the event values. Create a function inside App component:

      function handleStepperEvents(event){
      	console.log(event);
      	const value = event.detail.value;
      	if(value === '-'){ 
      		stepperValue--;
      	}else {
      		stepperValue++;
      	}
      }
      

      And set this handler for the Stepper element:

      <Stepper on:btnValue={handleStepperEvents} value={stepperValue}></Stepper>

      When Stepper emits the btnValue event, handleStepperEvents function will be executed.

      It’s already working!!! Let’s try one more trick. Inside App, create a variable like this:

      $: isEven = stepperValue % 2 == 0;

      The idea of the Dolar Sign ($) is that Svelte interprets it as re-run this code whenever any of the referenced values changes. Now place the Svelte conditional template after the <Stepper> element:

      {#if isEven}
      	<h1>{stepperValue} is EVEN!</h1>
      {:else}
      	<h1>{stepperValue} is ODD!</h1>
      {/if}

      You can check the complete code from this hand-on in THIS repository

Conclusion

Svelte has a lot of good practices that make our development process faster and more enjoyable in some ways but as this “frameworks” is kind of new, probably, will be harder to find discussions about problems and pre-made libs to use. Maybe I didn’t got problems with my project because it was too small and I would confront real world problems in bigger projects.

In my opinion, Svelte is a good shot if you are planning to do a personal project or you have a small and “closed scope” project at work. So, you could have the possibility to test and take the conclusions by yourself.

If you didn’t tried yet, don’t waste your time and go for it now! Remember that, every knowledge you get from an areas will make you better in others. Here you can find a good step-by-step tutorial: https://svelte.dev/tutorial/basics


Written by Bruno Haetinger. Go to my website

© 2021, Bruno Haetinger