Introduction to the

The first time I heard about Svelte was in the video of Vueconf sharing conference in 2019.6.8. Uvu mentioned that the update of Svelte adopted static analysis, which aroused great interest. Meanwhile, UVU also mentioned in the video that Vue3.0 also drew on some ideas. In addition, fibber slice rendering similar to React might not be implemented. Next, let’s share what I know about Svelte

What is a Svelte

To quote the official introduction:

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.Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.Copy the code

Svelte is an entirely new approach to building user interfaces. While traditional frameworks like React and Vue do most of the work in the browser, Svelte shifts that work to the compilation steps that occur when you build your application.

Instead of using techniques like virtual DOM differentials, Svelte writes code that updates the DOM externally when application state changes.

As we can see from the above, there is no virtual DOM inside Svelte, but the syntax is highly similar to Vue, and the update mechanism is statically analyzed at compile time, which means better screen load time and update performance.

Reduce the amount of code required to run the framework through static compilation. No runtime is required. Build some third-party plug-ins or SDKS

Disadvantages: single file size increases after compilation, and the ecology is not active, and there is no mature UI library

Svelte basic syntax

The official packaging tool is rollup, so take a look at Sevelte’s basic syntax to see how it differs from Vue

First take a look at the basic rollup configuration

import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser'; const production = ! process.env.ROLLUP_WATCH;export default {
	input: 'src/main.js',
	output: {
		sourcemap: true,
		format: 'iife',
		name: 'app',
		file: 'public/bundle.js'
	},
	plugins: [
		svelte({
			dev: !production,
			css: css => {
				css.write('public/bundle.css');
			}
		}),
		resolve({ browser: true}), commonjs(), ! production && livereload('public'),
		production && terser({
			compress: false// Disable code compression in order to better see the principle of compiled code:false,
			ie8: true// Support ie8})], watch: {clearScreen:false}};Copy the code

Get a feel for basic grammar

/ / App. Svelte < div > < p > {title} < / p > < img SRC = {SRC} / > < / div > < script > / / variable inside the scope statementlet title = 'Sevelte'
    let src = 'XXX'
</script>
<style>
    div {}
</style>Copy the code

How about this? Like Vue, we can define template variables directly inside the script tag. Each script tag corresponds to the scope of the current component

// App.svelte
<div>
    <p>{title}</p>
    <img src={src} />
</div>
<script>
    import { onMount } from 'svelte'; // Declare variables inside the scopelet title = 'Sevelte'
    let src = 'XXX'
   onMount(() => {
       console.log('the component has mounted'); }); </script> <style> div {} </style>Copy the code

Svelte also has a lot of features, such as event passing, component passing, animation transition, etc. You can go to the official website.

Svelte working mechanism

The amount of runtime code built into Svelte after compilation is actually very small, about 200 lines uncompressed, and its core updates and creation are concentrated in two functions create_fragment and instance. The instance function creates and returns variables defined in the script tag. In Sevlte, called CTX context, the createFragment function returns a list of hooks to create, update, and destroy. Using closures, it can accurately remember each DOM node and update it for each DOM node

let title = "Sevelte";
let src = "XXX";
function instance($$self) {
	onMount(() => {
		console.log("the component has mounted")});return{}} // Create a nodefunctionCreate_fragment (CTX) {var div, p, t0, t1, img;return{/ / create to createc() {
			div = element("div");
			p = element("p");
			t0 = text(title);
			t1 = space();
			img = element("img");
			img.src = src;
			div.className = "svelte-ums2o4"}, // mounts m(target, anchor) {insert(target, div, anchor); append(div, p); append(p, t0); append(div, t1); Append (div, img)}, p: noop, I: noop, o: noop, //destroy destroy d(detaching) {if (detaching) {
				detach(div)
			}
		}
	}
}
Copy the code

Svelte and Vue update performance analysis and comparison

It takes 60ms for Svelte and 300ms for Vue, and the performance is 5 times better than vue. however, the ability of Svelte to build large projects is unknown.

After Vue3.0 comes out, old projects may not be updated in time or cannot be updated. In case of performance bottleneck, the following ideas can be referred to, and Svelte can be gradually adopted in existing programs. The combination of the two may improve partial performance

Use Svelte elegantly in Vue

This can be compiled with the help of svelte-loader

cnpm i svelte svelte-loader -S

Configure it in vue.config.js

. configureWebpack: config => { config.module.rules.push({test: /\.svelte$/,
        use: 'svelte-loader'})}...Copy the code

App.vue

<script>
    import main from './main.svelte'
    export default {
        data () {
            return {
                title: 'Svelte'
            }
        }
        render (c) {
            return c('div', [
                c('span', {
                    on: {
                        click () {
                            this.title = 'Under the Plane Tree'
                        }
                    }
                })
            ])
        },
        watch: {
            title (val) {
                this.main.$set({
                    title: val
                })
            }
        },
        mounted () {
            this.main = new main({
                target: this.$el,
                props: {
                    title: this.title
                }
            })
        }
    }
</script>Copy the code

Main.svelte

<div>{title}</div> <script> // throw props for placeholderexport let title = 'placeholder'
</script>Copy the code

conclusion

Just know Svelte, summary is limited, we in the development process of specific how to use, see the actual business scenario.