In the 2020 You Don’t Know Svelte series, we will cover the basic uses, features, pros and cons, fundamentals and source code analysis of the Svelte framework.

directory

  • First article 👉 It’s 2020 and you Still Don’t Know Svelte (1) — First Introduction to Svelte
  • Second article 👉 It’s 2020 and you don’t know Svelte (2) — Updated Rendering Principles
  • The third article 👉 It’s 2020 and you don’t know Svelte (3) — Dirty Value Detection, DOM Update (to be continued)
  • 4 👉 It’s 2020 and You Don’t Know Svelte (4) — Long List Processing (to be continued)
  • Article 5 👉 It’s 2020 and you Don’t Know Svelte (5) — A Preliminary Study of Compilation Principles (to be continued)
  • Article 6 👉 It’s 2020 and You Don’t Know Svelte (6) — Implementing a Svelte Compiler (to be continued)

The front end is a fast-growing industry with many wheels. In recent years, as the React, Vue, and Angular versions of the three frameworks stabilized, the iteration of the front-end stack seemed to slow down. Fiber was released in React 16, and Vue 3.0 was in its infancy.

Looking ahead, what frameworks are likely to challenge React or Vue? We think the up-and-coming Svelte should be one of those options.

You may say, Vue, React it doesn’t smell good, don’t worry, let’s slowly read ~

Svelte frame that magically disappears

Svelte is [Svelte], meaning slim and slim, is a hot new front-end framework.

In the recent State of JS Survey of 2019, it was predicted as an emerging technology that could replace other frameworks like React and Vue over the next decade. If you’re not sure if you should know about Svelte, take a look at some of the trends in Svelte

Developer satisfaction

Developer interest

Market share

Of course, don’t panic if you haven’t heard of it yet, as Svelte is still a niche development framework that hasn’t caught on in the community yet. 24.7% of developers had not heard of the framework, and 44.9% had and were willing to try it out.

Judging from the scale of companies using the framework, sVELte is not widely used in large companies, which may be related to the lack of sVELte ecological environment and surrounding areas. Svelte is often used by small companies, probably because it’s easy to get started

The man behind it — Rich Harris

Svelte is written by front wheel guy Rich Harris, who is also the author of Rollup (again). Rich Harris himself has a wonderful talk about Svelte called “Rethinking ReActivity”, YouTube link www.youtube.com/watch?v=AdN…

The core idea of Svelte was to “reduce the amount of code at runtime through static compilation”, that is, traditional frameworks such as Vue and React must introduce runtime code for virtual DOM and DIff algorithms. Svelted is fully integrated into JavaScript, and all runtime code for the application is included in bundle.js. You don’t need to import additional runtime code other than the component itself.

The use of SVELte is very flexible. You can use the entire build architecture of Svelte throughout your project, add Svelte incrementally to your code, and distribute Svelte components as separate NPM packages

What are the advantages of Svelte compared with Vue and React

Said so much, really can’t learn how to do.

React Vue and Svelte React Vue

No Runtime — No Runtime code

React and Vue are runtime-based frameworks. The framework itself relies on code that is packaged into the final build. When the user does various things on your page to change the state of the component, The framework runtime updates the view by calculating which DOM nodes need to be updated based on the new component state.

This inevitably increases the volume of the package, and some of it inevitably increases in volume, so what is the approximate volume of the package? Take a look at the data below:

As can be seen from the table above, the smallest Vue of commonly used frameworks has 58K, while React has 97.5K. To be honest, this volume is a bit large. Let’s say we develop a small component SDK using React. Even though the logic inside is very simple, the bundle size can easily start at 100K.

This is not much for a large backend management system, but for scenarios where client-side loading performance is particularly important, 100K for a component is still too large. Here are Jacek Schae’s statistics, using the mainstream frameworks in the market to write the same Realword application:

From the statistics above, Svelte is amazing! It’s only 9.7 KB! Sure enough, magic disappears UI framework, well deserved name.

As you can see, the bundle size of Svelte is 1/4 that of Vue and 1/20 that of React

Less-code — Write Less Code

One of the dreams of developers is to type less code. Because less code often means better semantics and less chance of writing bugs.

When writing the Svelte component, you’ll find that it takes much less code than Vue or React. React differs from Svelte in the following example:

  1. ReactThe code of
const [count, setCount] = useState(0);

function increment() {
  setCount(count + 1);
}
Copy the code
  1. SvelteThe code of
let count = 0;

function increment() {
  count += 1;
}
Copy the code

The latest hooks of version 16 are used, but the code is still redundant compared to svelte.

In React, we use either the useState hook or setState to set the state. In Svelte, the assignment operator can be used directly to update the state.

Here are Jacek Schae’s statistics on the number of lines required for each framework to write the same Realword application:

Vue and React are tied, Svelte is way ahead, 1000 lines less code.

Hight-Performance: High Performance

What ??

In the Virtual Dom has been a standard front-end framework today, Svelte does not need Virtual Dom, how can it ensure high performance?

Take your time.

The performance evaluation

In A RealWorld Comparison of Front-end Frameworks with Benchmarks, Jacek Schae wrote Benchmarks to write A RealWorld application using A mainstream Front End framework, Using Chrome’s Lighthouse Audit, Svelte was slightly worse than Vue, but better than React

Isn’t that surprising? Another front-end framework performance comparison project gave the same answer. Github.com/krausest/js…

Why is Svelte performing well, at least not as badly as we expected? We’re going to analyze it bit by bit.

Is Virtual Dom really efficient

Rich Harris did not use the Virtual DOM because he felt that the Virtual DOM Diff process was very inefficient.

In his article “Virtual DOM is pure overhead, the original connection here, www.sveltejs.cn/blog/virtua… There’s an introduction, if you’re interested,

One reason people find Virtual DOM efficient is that it does not manipulate native DOM nodes directly. In browsers, JavaScript is very fast in modern engines, but DOM itself is a very slow thing. When you call the native DOM API, the browser needs to be exposed to the native DOM implementation in the context of the JavaScript engine, which has a considerable performance cost.

However, Virtual DOM can sometimes do a lot of useless work, as many components are re-render “for no reason”.

To fix this, React provides pureComponent, shouldComponentUpdate, useMemo, and useCallback for developers to worry about which subtrees need to be rerendered and which ones don’t. In essence, React was too flexible with its JSX syntax. It didn’t understand what developers meant when they wrote code and couldn’t optimize it.

So how does Svelte solve this problem?

React uses the JSX syntax because it does not understand the meaning of data and cannot be optimized.

Svelte uses the Templates syntax (similar to Vue), which is more strict and semantic and can be optimized at compile time.

So why does the Templates syntax solve this problem?

Advantages of Template

About JSX and Templates, can be seen as two different front frame render mechanism, interested students can look especially rain stream of speech “seek a balance in the design of the frame” www.bilibili.com/video/av800…

On the one hand, JSX’s representative framework is React and all the React-like libraries, such as pre-Act, Stencil, Infernal, etc. Templates, on the other hand, are typical solutions like Vue, Svelte, and Ember, all of which have their strengths and weaknesses.

JSX pros and cons

JSX has the full expressiveness of JavaScript, which is very expressive and can build very complex components.

But the flexible syntax also means that the engine is hard to understand and can’t predict the user intent of the developer, making it difficult to optimize performance. You would probably write code like this:

When working with JavaScript, it’s impossible for the compiler to hold on to everything that might happen because JavaScript is too dynamic. There have been a lot of attempts at this, but it’s inherently hard to provide safe optimizations.

So React chose to optimize by introducing the concept of scheduling concurrent time slices at runtime, without reducing the rendering effort, but instead making it “look” like the user won’t get stuck.

Advantages and disadvantages the Template

By definition, templates are a very constrained language, and you can only write templates in a certain way.

For example, when you write code like this, the compiler can immediately say, “Oh! The order of the P tags doesn’t change, the ID doesn’t change, the class doesn’t change, the only thing that changes is this.

At compile time, the compiler can make more predictions about your intentions, giving it more room to perform optimizations.

Let’s see that when SVELTE compiles code, it compiles the template into directly executable javascript code.

In the template on the left, everything else is static, except the name that may change.

The p function on the right is the final product of the compilation and is called when there is dirty data. The only thing p does is call a native method to update t1, the native DOM node, when name changes.

For details, see the second article in this series.

section

Back to the original question, we just want to know which algorithm is faster, SVELTE or VDOM Diff?

Depending on the complexity of the component, VDOM Diff takes longer and SVELTE performs better when there are more elements in the component.

Svelte disadvantage

When building a large front-end project, there are many more things to consider when choosing a framework.

Svelte is still in its infancy, and there is no complete solution for unit testing necessary for large projects. Svelte is currently used in large applications and needs to be reviewed with caution.

Compare to the Vue and React frameworks

category Svelte Vue React
The UI component library Material Design (frankly, not easy to use) Element UI / AntD AntD / Material design
State management Website with Vuex Redux/MobX
routing Svelte-router Vue-router React-router
Server side rendering support support support
Testing tools There’s nothing on the official website @vue/test-utils Jest

There are some other major points of note that we found when we used Svelte to develop large, medium – and corporate-level projects

  • There is no mature UI library like AntD. For example, if the demand side wants to add a toast prompt, or pop up a window, PM: “Very simple, don’t need to issue the UI draft, just use the previous style.”

    But… Em.. Svelte needs to “copy” a toast or popup component from zero, which can lead to extra development and extra work.

  • Svelte natively does not support preprocessors, such as LESS/SCSS, and requires a separate webPack loader configuration.

  • Svelte native scaffolding has no directory division

  • Typescript is not currently supported, although officially it will be, but we don’t know when.

It is also important to note that frameworks such as React/Vue have runtimes that add bundle.js to the first screen. However, as the project gets bigger, the runtimes make up a smaller proportion of bundle.js. At this point we need to consider whether there is a code generated by Svelte that is greater than the threshold generated by React and Vue

Svelte usage

To be honest, Svelte usage here, do not want to do official website porter. On the one hand, the official website of Svelte has been done very well, you can run the demo directly; On the other hand, the syntax itself is very simple. I was able to write a demo after watching it all afternoon. I suggest you also go to the official website svelte.dev/tutorial/ba…

Here is a brief review of the missing points in the official website of Svelte:

Responsive data

Both Vue and Svelte are template syntax, and everything is very similar to native writing.

Data is reactive by default, using {} directly in HTML to retrieve the data defined in JS.

<script>
	let name = 'world';
</script>

<h1>Hello {name.toUpperCase()}!</h1>
Copy the code

Adding events is also handy:

<script>
	let count = 0;

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

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

Here is a brief review of the missing points in the official website of Svelte:

component

Child Svelte components are passed up through emit events, and if there are multiple components, they must be passed down so that the upper component can catch them. Svelte provides grammar sugar

<script>
    import Inner from './Inner.svelte';
</script>
// Just pass the layer in the middle, 'on:message'
<Inner on:message/>
Copy the code

The life cycle

OnMount indicates a hook to be mounted. Asynchronous requests are recommended for server rendering

import { onMount } from 'svelte';
onMount(async() = > {const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`);
  photos = await res.json();
})
Copy the code

OnDestroy destroys, for example, the subscribed global Store, otherwise memory leaks

import { onDestroy } from 'svelte';
const unsubscribe = count.subscribe(value= > {
        count_value = value;
});
onDestroy(unsubscribe)
Copy the code

The tick() method, similar to $nextTick() in Vue, waits for the DOM node to be updated

await tick();
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;

Copy the code

Global data flow

Initialize the

/store/inex.js

import {writable} from 'svelte/store'
export const xx = writable(0);

Copy the code

To subscribe to

xx.subscribe((value) = > {
  localValue = value;
})

Copy the code

update

xx.update((n) = > {
  return n + 1
})

Copy the code

reset

xx.set(0)

Copy the code

class

You can use three eyes

<button
    class="{current === 'foo' ? 'active' : ''} box"
    on:click="{() => current = 'foo'}"
>foo</button>

Copy the code

Or I could write it more succinctly,

<div class:xxx="{activ}" class="box"></div>

Copy the code

conclusion

This paper mainly introduces the current development trend of Svelte, advantages and disadvantages of Svelte. If in the right project, bold use it, I wish you a happy use.

Finally, Bytedance is hiring everyone!!

Bytes to beat (hangzhou) | Beijing | Shanghai a lot of hiring. The benefits are great and the salary is second to BAT. No clock at work, afternoon tea every day, unlimited free snacks, three free meals (I read the menu, hairy crab, abalone, scallop, seafood, grilled fish fillet, beef with black pepper, curry, beef and spicy crayfish). Free gym, 16 inch roof with the latest MBP, monthly rental housing supplement. This is really a lot of opportunities, the number of research and development after the expansion of N times, good technical atmosphere, cattle, less overtime, still hesitate what? Send your resume to the email below, now!

Just a small JD, more welcome to add wechat ~

Front end JD

  • Advanced Front-end (Beijing) 👉 job.toutiao.com/s/WXjEDn

  • Front-end cross-end Applications (Beijing) 👉 job.toutiao.com/s/WXBG1s

  • Front-end Intern (Beijing) 👉 job.toutiao.com/s/WXBqne

  • Front-end Intern (Hangzhou) 👉 job.toutiao.com/s/WXM4oX

  • Advanced Front-end (Hangzhou) 👉 job.toutiao.com/s/WXfj3x

  • Advanced Front-end (Shanghai) 👉 job.toutiao.com/s/WX88rF

The JAVA part of JD

  • JAVA (Beijing) 👉 job.toutiao.com/s/WX2wPC

Continue to recruit a large number of front-end, server, client, testing, products, internship recruitment are wide to

Add wechat dujuncheng1, you can chat about life, please indicate from nuggets and where to post