Svelte

Introduction

  • Svelte provides a different approach to building web apps than some of the other frameworks covered in this module. While frameworks like React and Vue do the bulk of their work in the user's browser while the app is running and rely on their own library, Svelte shifts that work into a compile step that happens only when you build your app, producing highly optimized vanilla JavaScript.

  • The outcome of this approach is not only smaller application bundles and better performance, but also a developer experience that is more approachable for people that have limited experience of the modern tooling ecosystem.

  • Svelte sticks closely to the classic web development model of HTML, CSS, and JS, just adding a few extensions to HTML and JavaScript. It arguably has fewer concepts and tools to learn than some of the other framework options.

Rendering

  • Svelte achieves this through a mechanism called reactive declarations.

  • When you define a variable or a reactive statement using the let keyword in a Svelte component, Svelte internally keeps track of its dependencies. It does this by analyzing the code in the component's script block during the compilation phase.

  • When a dependency changes, Svelte knows that the component needs to be re-rendered. It updates the component's internal state and generates an optimized JavaScript code specific to that component, including the necessary updates to the DOM.

  • It generate pure js to listen to specific state to update the real dom directly

Life Cycle

onMount -> (update the view) beforeUpdate -> afterUpdate -> onDestroy

Reactive Declaration

<script>
	let count = 1;

	// the `$:` means 're-run whenever these values change'
	$: doubled = count * 2;
	$: quadrupled = doubled * 2;
	$: if (count >= 10) {
		alert(`count is dangerously high!`);
		count = 9;
	}
	
        $:count, (() => {
           console.log("count");
        })()

	function handleClick() {
	   count += 1;
	}
</script>

<button on:click={handleClick}>
   Count: {count}
</button>

<p>{count} * 2 = {doubled}</p>
<p>{doubled} * 2 = {quadrupled}</p>

Props

<script>
	import Nested from './Nested.svelte';
</script>

<Nested answer={42} />
<Nested />
<script>
	export let answer = 'a mystery';
</script>

<p>The answer is {answer}</p>

Store

<script>
	import { count } from './stores.js';
	import Incrementer from './Incrementer.svelte';
	import Decrementer from './Decrementer.svelte';
	import Resetter from './Resetter.svelte';

	let countValue;

	const unsubscribe = count.subscribe((value) => {
		countValue = value;
	});
</script>

<h1>The count is {countValue}</h1>
<script>
	import { count } from './stores.js';

	function decrement() {
		count.update((n) => n - 1);
	}
</script>

<button on:click={decrement}> - </button>
import { writable } from 'svelte/store';

export const count = writable(0);

Last updated

Was this helpful?