Recently, due to the business needs of the company, it may be necessary to develop a browser plug-in, and after investigating, it is found that plug-in UI development is essentially page development. So I started looking for a new toy (tool) that was very small and very fast. After all, any one of the three front-end frameworks to develop a browser plug-in is like a cannon at a mosquito. I don’t want to touch Dom manipulation, which is extremely inefficient. So I found this magic disappear UI framework which has been very popular abroad – Svelte.

What is Svelte

Svelte is a compiled front-end component framework. Instead of using the virtual DOM, the framework is compiled to provide an asynchronous response when application state changes.

Compiled framework

Any front-end framework has a runtime, and (in the case of Vue) it needs to carry at least the virtual DOM and diff algorithm in the browser. If you introduce Vue scripts directly into the page, you also need to append Vue front-end compiler code. See Vue for an explanation of the different builds.

Svelte, on the other hand, decided from the start to translate much of the work that other frameworks do in the browser into the compile step in the build in order to reduce the amount of application code. It provides functionality on demand through static analysis (no import at all), but it also analyzes code that updates the DOM precisely based on your current changes to improve performance.

Let’s take the simplest code as an example.

// App.svelte <h1>Hello world! </h1> // main.js import App from './App.svelte'; const app = new App({ target: document.body }); export default app;Copy the code

In fact, the development version is compiled as (for simplicity, only parts of the code are analyzed, not all of the code)

// IIFE executes function expressions immediately
var app = (function () {
  'use strict';
  // Empty function, used for code that needs to provide a function
  function noop() {}// How many characters precede the current element's column
  function add_location(element, file, line, column, char) {
    element.__svelte_meta = {
      loc: { file, line, column, char }
     };
  }
  //   
  // Operate dom helper functions to reduce the amount of code... (Equivalent to runtime)
  function insert(target, node, anchor) {
    target.insertBefore(node, anchor || null);
  }
  function detach(node) {
    node.parentNode.removeChild(node);
  }
  function element(name) {
    return document.createElement(name);
  }
  function children(element) {
    return Array.from(element.childNodes);
  }
  // Asynchronously process the modified component
  // (Actually this code is not needed in the current scenario, can be removed, but not necessary)
  const dirty_components = [];
  const binding_callbacks = [];
  const render_callbacks = [];
  const flush_callbacks = [];
  const resolved_promise = Promise.resolve();
  let update_scheduled = false;
  function schedule_update() {
    // ... 
  }
  function add_render_callback(fn) {
    // ...    
  }
  function flush() {
   // ...  
  }
  function update(?) {}// Current file, development version
  const file = "src\\App.svelte";
  
  function create_fragment(ctx) {
    let h1;

    const block = {
      / / create
      c: function create() {
    	h1 = element("h1");
    	h1.textContent = "Hello world!";
    	add_location(h1, file, 1.9.10);
      },
      // Mount the element you just created
      m: function mount(target, anchor) {
        // The target above is document.body
    	insert_dev(target, h1, anchor);
      },
      // The dirty component is called in the update above
      p: noop,
      / / delete
      d: function destroy(detaching) {
    	if(detaching) detach_dev(h1); }}; dispatch_dev("SvelteRegisterBlock", {
      block,
      id: create_fragment.name,
      type: "component".source: "",
    	ctx
    });
    return block;
  }  
}());
Copy the code

As you can see, after the development version is compiled, all the code you write becomes the native JS manipulation Dom. It is also highly readable (which is very important). My blog summary of optimizing Web application performance also shows that improving code coverage is the most profitable of all optimization mechanisms. This means less code can be loaded, less code executed, fewer resources consumed, and fewer resources cached. Optimization on demand for static analysis will also be provided in Vue 3.

It is worth noting that because Svelte is a compiled framework, both development and production environments produce the same files in the same folder (at least when I started writing, 2020-1-4). If the front end doesn’t use a build deployment tool, or if I just want to develop a browser plug-in, it’s possible to forget to do the build command because the folder already exists, and use the code generated from the development version incorrectly.

Meanwhile, Svelte directly supports a variety of compilation configuration projects. Just add options to the component:

<svelte:options option={value}/>
Copy the code
  • Immmutable When you confirm that you are currently using immutable data structures, the compiler performs a simple reference equality (rather than object attributes) to determine whether the value has changed for better performance optimization. The default is false. When this option is set to true, if the parent modifies the object properties of the child, the child will not detect the change and will not be re-rendered.

    <svelte:options immmutable={true}/>
    Copy the code
  • Tag can compile handwritten Components into Web Components for use by other frameworks. It can be used according to the following. For Web Components, please refer to Ruan Yifeng’s Web Components tutorial. This is also an integral feature of the new framework.

    <svelte:options tag="my-custom-element"/>
    Copy the code
  • Accessors can add getters and setters for component props. The default is false.

  • A namespace is the namespace that the component will use, and one use is to specify a namespace for SVG.

When a language’s capabilities are inadequate and the user’s operating environment does not support other options, the language becomes a “compilation target” language

Js was such a language a few years ago, when there was coffeeScript, which was more expressive, and Typescript, which was more restrictive. Over time, the front-end wants to compile not only at the programming language level, but also at the framework level.

Since the end of 2018, front-end frameworks have been moving more toward compilation. One is for stronger performance ability and performance gain, like Svelte, the other is to smooth the gap between multiple platforms, such as domestic small program frameworks Taro(React system, suitable for new projects), Mpx(wechat small program, suitable for old projects) and so on.

Higher performance

Compared with the compiled frameworks like Elm Imba and ClojureScript of the same type, Svelte is the most friendly to front-end partners in terms of toolchain and syntax expression. If you want to learn Svelte, you can look at the tutorial module provided by the official website. The friendliness of the official website of Svelte is also very good for beginners. Some specific syntax is described below.

State and two-way data binding

Let lets you set state, and bind:value lets you bind data.

<script> // let name = 'world'; Const inputAttrs = {// Input type is text type: 'text', // maxLength: 10}; </script> <! -- Name, while passing attributes can be used to make use of... Syntax to optimize --> <input {... inputAttrs} bind:value={name} /> <hr/> Hello {name}Copy the code

As you can see, the above code has easy two-way data binding and very powerful code representation.

Use of attributes

The parent component:

	
<script>
  import Hello from './Hello.svelte';
</script>
 
<Hello name="Mark" />
Copy the code

Hello components:

<script> // this can be accepted externally, but the name can also be changed internallyexport let name = 'World'; $: doubleName = name + name </script> <div> Hello, {name}! </div> <hr/> {doubleName}Copy the code

Direct interaction with components

This feature is what appeals to me the most, and I’ve used a lot of component frameworks. But any interaction with a component is written to the parent component as a business type component. For example, interactions between addresses (default addresses), and interactions between complex forms, the code looks like this:

Input component

<! <script context="module"> // const Map = new Map(); Export function clearAll() {map.foreach (clearfun => {clearfun()}); } </script> <script> import { onMount } from 'svelte'; Export let index; OnMount (() => {map.set(index, clear); }); Function clear () {value = ""} function clearOthers() {map.foreach ((clearfun, clearfun) key) => { if (key ! == index) clearfun(); }); </script> <div> <button on:click={clear}> bind:value={value}> {value} </div>Copy the code

App component:

<script> import Input, {clearAll} from './ input. svelte' </script> <div index='1'/> <Input index='2'/> <Input index='3'/> <Input index='4'/> <Input index='5'/> </div>Copy the code

This completes the interaction with components, which is very simple, but because the Module is global, all child components have global functionality, whether or not they are in the same parent component. If there are more than two modules on the same page, additional attributes need to be added to aid development. So this feature is a weapon that could hurt you.

other

Svelte has a lot of simple syntax and animations that I won’t cover here. Because it’s so simple, if you’ve used any other type of framework, you’ll probably be writing business code in a matter of hours. Of course, if I run into some inevitable problems during plug-in development, I’ll write about them and write another blog post.

Unavoidable faults

Svelte has been developed since version 3.0. In general, some of the development issues may not be there, but there is no major company support, so there may still be some inevitable bugs.

  • Do not support the TypeScript

  • The ecological environment is not good enough

  • The single-component file suffix svelte is too verbose

  • There are no build tools at the moment

  • If determines that the for loop is unusable (for compilation)

    {#if user.loggedIn} <button on:click={toggle}> Log out </button> {/if} {#if ! user.loggedIn} <button on:click={toggle}> Log in </button> {/if} {#each cats as { id, name }, i} <li> <a target="_blank" href="https://www.youtube.com/watch?v={id}"> {i + 1}: {name} </a> </li> {/each}Copy the code

To encourage the

If you think this article is good, I hope you can give me some encouragement and help me star under my Github blog. Blog address

Reference documentation

Svelte website