Starting:Cc log– Unpack Svelte

The React, Vue, and Angular frameworks still dominate the last day of 2019. They will probably still dominate next year, but they are still working on wheels 😄. Rich Harris, creator of rollup, is the most famous. The most recent project is Svelte, a Web framework.

Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.

Svelte is different in that:

  • The so-called “disappear and die” framework, as far as possible through static compilation to reduce the amount of code framework runtime, this article does not expand, interested can see Vue author Uta on Svelte’s answer to the question.
  • Do not use the Virtual Dom
  • Really responsive

Aside from the official website rhetoric, here’s what appeals to me:

  • The author has a wonderful video: Rethinking Reactivity
  • Super sweet syntax (similar to Vue).
  • Built-in responsive Store solution (similar to RxJS, but simplified and easy to learn)

After a much longer and meander than expected development of Chrome Extension (TODO: Ghost-MDE Introduction), I’d like to write this Svelte out of the box, with a brief personal opinion:

  • The grammar is amazing and interesting (in a positive sense, like xiaoyao Pai kung fu versus Shaolin kung fu).
  • Recommended for small amateur projects (speed of writing and build code size are advantages).
  • Formal, company-level, not recommended in Chinese circles (not much information, some concepts are different from the “unwritten standard” like React).

Svelte basis

Svelte is basically used in a similar way to Vue. The HTML, CSS, and JS of a component are written in a.svelte file.

<script>
	let count = 0;

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

<style>
	button {
	  background: #ff3e00;
	  color: white;
	  border: none;
	  padding: 8px 12px;
	  border-radius: 2px;
	}
</style>

<button on:click={handleClick}>
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Copy the code

Template syntax

if

{#if porridge.temperature > 100}<p>too hot! </p> {:else if80 > porridge.temperature} <p>too cold! </p> {:else} <p>just right! </p> {/if}
Copy the code

Loop syntaxeach

{#each items as item, i}
	<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
Copy the code

Asynchronous loadingawait

You can even use promises directly in the template

{#await promise}<! -- promise is pending --> <p>waitingforthe promise to resolve... </p> {:thenvalue} <! -- promise was fulfilled --> <p>The value is {value}</p> {:catch error} <! -- promise was rejected --> <p>Something went wrong: {error.message}</p> {/await}Copy the code

Elements of instruction

The element directive in Svelte allows you to easily manipulate elements.

  • Event Listener on: eventName:on:eventname|modifiers={handler}
  • Bind :property:bind:property={variable}
    • You can even have read-only bindingsclientWidth.clientHeight.offsetWidth.offsetWidth
  • Bind :group={variable}
  • Get an instance of a DOM node or component, bind:this:bind:this={dom_node}
  • The class binding,div class="{active ? 'active' : ''}">... </div>.<div class:active class:inactive={! active} class:isAdmin>... </div>
  • And commonly usedslot

In general, the svelte basic syntax is really easy to use and easy to get started with. See the Svelte API documentation for more.

Magic symbol$

Svelte cleverly uses a useless $symbol in JS to express the response.

let a = 0;
$: b = a + 5;
Copy the code

The value of variable B changes as a changes. Even more complex code can be wrapped up quickly.

let a = 1;
let b = 2;
$: {
	if (a+b > 10){
		// do something
	}
}
Copy the code

Svelte life cycle

Web frameworks, especially componentized frameworks, naturally have a life cycle, and Svelte is no exception:

  • OnMound:onMount(callback: () => () => void)
  • beforeUpdate: beforeUpdate(callback: () => void)
  • afterUpdate: afterUpdate(callback: () => void)
  • onDestroy: onDestroy(callback: () => void)

The behavior is basically the same as what you know about Vue and React.

Svelte dispatch, Context

The composition of Svelte components, and the communication of components is very similar to that of Vue, with attributes passing from top to bottom? Props pass, child component up dispath event.

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();
</script>

<button on:click="{() => dispatch('notify', 'detail value')}">Fire Event</button>
Copy the code

Svelte provides the context, but in combination with the Svelte Store, it’s easy to use.

import { writable } from "svelte/store";
const nameStore = writable("name");

setContext("name", nameStore);

function changeName() {
	nameStore.set("name2");
}
Copy the code
<div>
	<p>{$name}</p>
</div>


<script>
import { getContext } from "svelte";
const name = getContext("name");
</script>
Copy the code

So far so good, here’s where Svelte really gets interesting 🤓

Svelte store using

Modern data-driven framework, the unavoidable is the state management library, Svelte is to provide a quite sophisticated and easy to use scheme, Svelte Store.

Svelte Store is similar to RxJS, but keeps its responsiveness as low as possible (not as high a bar as RxJS, or even as rigid as Redux), to Svelte 👍👍👍.

writable

You can use writable to create a writable store.

store = writable(value: any, (set: (value: any) => void) => () => void)
Copy the code

It’s easy to use

<div>{$count}</div>
<script>
import { writable } from 'svelte/store';

const count = writable(0);

count.subscribe(value => {
	console.log(value);
}); // logs '0'

count.set(1); // logs '1'

count.update(n => n + 1); // logs '2'
</script>
Copy the code
  • subscribeMethod to subscribe to store changes
  • setMethod to set the value,updateMethod uses functions to get the value in store and set a new value.
  • HTML template$To reference store.

readable

store = readable(value: any, (set: (value: any) => void) => () => void)
Copy the code

Use readable to create stores that can be externally writable.

import { readable } from 'svelte/store';

const time = readable(new Date(), set => {
	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return () => clearInterval(interval);
});
Copy the code

derived

Derived is what really fires the store, it takes the store and converts it to a new store, which is actually what many operators in RxJS do, which is not as powerful, but also lowers the bar to use.

Store = derived(a, callback: (a: any) => any) // Can accept single store store = derived([a,...b], callback: ([a: any,...b:) any[]],set: (1) value: any) = > void) = > void | () = > void, initial_value: any) / / can also accept the multiple storeCopy the code

I’m not going to expand too much here, but PERSONALLY I think That Derived is probably the best thing about Svelte, that you can use it to make your code look great.

A little bit of Svelte discomfort

  • No Typescript support, 2020. This is a serious bug.
  • The Svelte stroe only “responds” when the value changes. This is different from RxJS.
  • Some abnormal writing may not trigger the response. For example, passing a response variable through a function parameter will result in no response… This may make you very upset 😄

conclusion

In general, Svelte provides an idea and development experience beyond the junior year framework that is worth learning from and encouraged to use in small amateur projects.