Lets Learn SvelteJS || Framework for future

Lets Learn SvelteJS || Framework for future

Github : https://github.com/tkssharma/lets-play-with-sveltejs Playlist : https://www.youtube.com/watch?v=lxzyI4WoffM&list=PLT5Jhb7lgSBMqIuNda0gGNEiMS-ahGJM1

Lets explore Svelte JS and all its concepts

To use Svelte, you need to have Node.js installed because all the tooling we're going to use is based on Node. Check out my tutorial how to install Node.js if you don't have it already!

And make sure it's the latest version (how to update Node.js).

If you don't want to install Node, the Svelte website provides a very cool REPL (Read-Eval-Print Loop) at https://svelte.dev/repl. It's handy to test small Svelte apps and to experiment with things. Node installs the npx command, which is a handy way to run Node commands. In particular, we're going to run this:

npx degit sveltejs/template firstapp

This will download and run the degit command, which in turn downloads the latest code of the Svelte project template living at https://github.com/sveltejs/template, into a newly created firstapp folder.

Make sure that git is installed on your machine and added to the PATH variable, otherwise the degit command won't work. In case things are still not working out for you, you can alternatively 'Clone or download' the template project and then delete the hidden .git folder. This is basically the same thing that the degit command does (only difference is that the folder is called template instead of firstapp).

Now go into that firstapp folder and run npm install to download the additional dependencies of the template. At the time of writing, these are the dependencies of that project template:

"npm-run-all"
"rollup"
"rollup-plugin-commonjs"
"rollup-plugin-livereload"
"rollup-plugin-node-resolve"
"rollup-plugin-svelte"
"rollup-plugin-terser"
"svelte"

As you can see, it's the Svelte core, plus Rollup (a Webpack alternative) and some of its plugins. Plus npm-run-all, a CLI tool that is used to run multiple npm scripts in parallel or sequential.

We're now ready to run our Svelte site in development mode, by running

npm run dev

This will start the app on localhost, on port 5000, by default:

Svelte is a UI framework. Unlike react and friends (or should I say enemies), svelte does not use any virtual DOM. Rather it compiles your code to tiny framework less vanilla js. This makes the app really fast. Also not to mentiont the incredible guide the svelte-tutorial

Components in Svelte 🐻‍❄️ So let's start with what I think the makes all the frameworks worth using, Components. I think making your UI into little components makes UI really easy to manage and program. I am not a frontend guy honestly but I like the fact that I can have multiple elements divided in my UI. Again this post is not on why frontend frameworks are good.

In svelte the components are files with .svelte extension. Not a great change that's just another syntax ( also btw why do all these frameworks create their own custom syntax). But wait you don't have to export the components here. Suppose you have this parent called App.svelte.

<script>
// here is js comment :)
 import MyComponent from "path-to-component/MyComponent.svelte"
</script>

<MyComponent />
and here's MyComponent.svelte:
<!--- MyComponent.svelte --->
<p>
This is my component
</p>

Props in Svelte 🐻

You thought that svelte does not have props. Svelte has export statements to export props or as I like to say 'recognize props' (Not a proper term don't use it).

This is a child component let's call it Weatherdetails.svelte

<!--- Weatherdetails.svelte --->
<script>
    export let answer;
</script>

<p>The weather is {answer}</p>
Let's call the parent component App.svelte.
<script>
    import Weatherdetails from './Weatherdetails.svelte';
</script>

<Weatherdetails answer="humid :\"/>

I like how svelte devs explain how this in not javascript-ish.

this may feel a little weird at first. That's not how export normally works in JavaScript modules! Just roll with it for now — it'll soon become second nature.

I am hoping to see it become second nature :)

Reactivity in Svelte 🐨 Again as svelte describes it does not uses any complex state management.According to the svelte website "At heart of svelte is a powerful system of reactivity". This means that you can call javascript inside your html (not literally I just like to think of it this way). Here's the reactivity explained in the good ol' counter app.

<script>
let counter = 0
function increaseCount(){
  count += 1
}
</script>

<h1> Current Count : {count} </h1>
<button on:click={increaseCount}> 
    click to increase count ! 
</button>

Wow that was quick.

Here you can see it's like react state just has a lot less boiler-plate. Also svelte introduces a special thing which is somewhat similar to useEffect hook in react.

<script>
let counter = 0
function increaseCount(){
  count += 1
}
$: square = count * count
</script>

<h1> Current Count : {count} </h1>
<button on:click={increaseCount}> 
    click to increase count ! 
</button>
<p>The square of {count} is {square} </p>

Here the $ looks a little weird. But this basically tells svelte compiler that whenever any of referenced value statement changes do this thing.

Conditional rendering and Await in markup 🐑 To render text conditionally svelte applies a little bit custom markup syntax.

<script>
    let user = { loggedIn: false };

    function toggle() {
        user.loggedIn = !user.loggedIn;
    }
</script>

{#if user.loggedIn}
    <button on:click={toggle}>
        Log out
    </button>
{:else}
    <button on:click={toggle}>
        Log in
    </button>
{/if}

So here according to svelte website again

A # character always indicates a block opening tag. A / character always indicates a block closing tag. A : character, as in {:else}, indicates a block continuation tag. Don't worry — you've already learned almost all the syntax Svelte adds to HTML.

Now this the normal part. Jinja follows same pattern. But wait we have more. Introducing the asynchronous await in markup. Wanna see how this looks. Here

<script>
    async function getCatImage() {
        const res = await fetch("https://api.thecatapi.com/v1/images/search");
        const jsonres = await res.json();
        const imageUrl = await jsonres[0].url

        if (res.ok) {
            return imageUrl;
        } else {
            throw new Error("No image found or something went wrong");
        }
    }

    let promise = getCatImage();

    function handleClick() {
        promise = getCatImage();
    }
</script>

<button on:click={handleClick}>
A random cat 🐈
</button>

<!-- Awaitting the response -->
{#await promise}
    <p>...waiting</p>
{:then src}
    <img {src} alt="a cat"/>
{:catch error}
    <p style="color: red">{error.message}</p>
{/await}

Honestly I was really impressed when I first saw this. This is was so cool see.

Here's the working demo 🐈✨ :

Lifecycle ♻️

Yay! Lifecycle methods. Lifecycle in svelte is quite similar to react.

The most common lifecycle method is onMount. This is basically a function that is executed when component is rendered. onDestroy is function that runs when a component is destroyed. beforeUpdate and afterUpdate do what there names suggest run a function before or after the component is rendered. These were quite similar to the lifecycle methods in react.

The last lifecycle method is tick. The tick function is unlike other lifecycle methods it can be called anytime. It returns a promise that resloves as soon as any pending state changes have been applied to DOM. In simpler words you can say that when you want to ensure that state immediately updates you can run tick function.

Binding the state 🐲

Do you guys remember the old class based components in react where you had to bind the function to specific component. Svelte does something similar but more simpler looking.

<script>
    let name = 'world';
</script>
<input bind:value={name}>

this will change the value of name with input provided. The bind-action (in this case value) may change from element to element.

This Binding One binding that applies to all is this. You can compare it to something like useRef hook from react. It provides you a reference to a rendered element.

For example you can do something like this ✨:

And now I can use canvas api just like native javascript. I really like the canvas api and wanted to use react but I was not able to get that level of simplicity as in native js. Svelte makes it almost similar to native js

Store 🦄

Store is a way to manage state across the whole app. You may pass down state to childrenusing props but the when you have to share state across various parent components you can use store. A breif overview of stores can be given this way

<!-- Store.js : Here we can initialize store -->
import { writable } from 'svelte/store';

export const count = writable(0);
<!-- And let's subscribe this store to App.svelte -->
<!-- so I can just do --> 
<script>
import { count } from './stores.js';

let count_value;

count.subscribe(value => {
        count_value = value;
});
</script>

<h1>The count is {count_value}</h1>

Stores are a bit complex topic ( not really quite simple once you go through the tutorial ) And I am not gonna cover everything about them in this post. So that may be a different blog for different time. Meanwhile if you really wanna know just go on to the tutorial

Inbuilt Transitions and animations 🐳 This one surprised me. Svelte has inbuild transitions, animation and motions.

<script>
    import { blur } from 'svelte/transition'
    let visible = true;
</script>

<label>
    <input type="checkbox" bind:checked={visible}>
    visible
</label>

{#if visible}
    <p transition:blur>
        Fades in and out
    </p>
{/if}

This piece of code shows how simple it is to implement the fade transition. This is all I wanted from frontend frameworks. Isn't this amazing. I just love svelte now. There are more animation related stuff which you can again see in the svelte-tutorial

Here's a little navbar that I made using svelte builtin transitions :

Conclusion 💫

This was just a breifing of svelte. There is so much more that I didn't cover. I have already link svelte tutorial like 10 times in this blog so not gonna do It again. This post really helped me understand lot of stuff about svelte and also react.

Comments