You haven’t heard of sveltejs yet?

Time:2020-7-5

React, Vue and angular almost occupy the majority of web development, but svelte has gradually attracted more and more people’s attention in the last half year. What’s so amazing about the svelte framework? This article will analyze the reason why svelte is popular, and use svelte to build a simple Bookstore application (bookshop) to help you quickly get started with this framework.

Why does svelte fire?

To know why svelte is so popular, first look at the problems with react and Vue frameworks.

Big runtime – large runtime

React and Vue are runtime based frameworks. The so-called runtime based framework is the framework itself, and the code will be packaged to the final bundle.js And is sent to the user’s browser. When the user changes the state of a component through various operations on your page, the runtime of the framework will calculate which DOM nodes need to be updated according to the new component state, so as to update the view. How big are these runtime codes? We can see the statistics of some communities

Name Size
Ember 2.2.0 435K
Ember 1.13.8 486K
Angular 2 566K
Angular 2 + Rx 766K
Angular 1.4.5 143K
Vue 2.4.2 58.8K
Inferno 1.2.2 48K
Preact 7.2.0 16K
React 0.14.5 + React DOM 133K
React 0.14.5 + React DOM + Redux 139K
React 16.2.0 + React DOM 97.5K

As can be seen from the above table, the smallest Vue is 58K and react is 97.5k. In other words, if you use react as a development framework, even if your business code is very simple, your first screen bundle size should start at 100k. Of course, 100k is not very big, but things are relative. Compared with large-scale management systems, 100k is certainly nothing. But for those applications that are sensitive to the loading time of the first screen (such as Taobao and Jingdong homepage), 100k bundle size will really affect the user experience in some bad network environment or mobile terminals. So how to reduce the runtime code size of the framework? The most effective way to reduce runtime code is to not use runtime at all. In fact, looking back on the history of web development, when we used jQuery and bootstrap a long time ago, didn’t our code contain runtime? When the data changes, the native DOM node can be changed directly through JavaScript, without a series of diff and react fiber processes of the framework. At this point, you may ask, is it really necessary to go back to the era of slash and burn cultivation to reduce bundle size? Is there a way for me to write code in a syntax close to react and Vue without the framework runtime. This is exactly what svelte wants to do. It adopts the concept of compiler as framework and puts the concept of framework at compile time rather than runtime. When the application code you write is packaged with tools such as webpack and rollup, it will be directly converted into JavaScript’s native operation on DOM nodes, so that bundle.js The runtime that does not contain the framework. So how much can svelte reduce the bundle size? Here are the statistics of realworld:
You haven't heard of sveltejs yet?
From the above chart, we can see that for applications with the same function, svelte’s bundle size is 1 / 4 of Vue and 1 / 20 of react! From this data, svelte framework has greatly optimized the bundle size.

Inefficient virtual DOM diff

what? Isn’t virtual DOM always efficient? In fact, the efficiency of virtual DOM is a misunderstanding. One of the reasons virtual DOM is efficient is that it doesn’t directly operate on native DOM nodes, because it consumes a lot of performance. When the component state changes, it will use some diff algorithm to calculate the real view change of the data update, and then only change the DOM nodes that need to be changed. People who have used react may realize that react is not as efficient as expected. Sometimes the framework does a lot of useless work, which is reflected in the fact that many components are re rendered for no reason. Note that re render is different from operating on the native DOM! The so-called re render means that the render method of class component defined by you is re executed, or your component function is re executed. Components are re rendered because the efficiency of virtual DOM is based on the diff algorithm. If there is a diff, the component must be re rendered to know whether the new state or the old state of the component has changed, so as to calculate which DOM needs to be updated. You may say that the react fiber has come out. This should not be a problem? In fact, the problem solved by the fiber architecture is to prevent the re rendering of components and the reconcile process from blocking the execution of the main thread. The problem of component re rendering still exists. According to the feedback, after the react hooks come out, the re rendering of components becomes more frequent. Because the framework itself is difficult to avoid useless rendering, react allows you to use APIs such as shouldcomponentupdate, purecomponent and usememo to tell the framework which components do not need to be re rendered, but this also introduces a lot of boilerplate. If you want to know more about the problems existing in virtual DOM, you can take a look at the article virtual DOM is pure overhead.

So how to solve the problem of inefficient virtual DOM algorithm? The most effective solution isVirtual DOM not used! In fact, as a framework, the problem to be solved is that when the data changes, the corresponding DOM node will be updated (reactive). Virtual DOM needs to compare the state of new and old components to achieve this goal. In fact, a more efficient way is toWhen the data changes, the corresponding DOM node is updated directly

if (changed.name) {
  text.data = name;
}

That’s what svelte did. Svelte will convert each state change into the corresponding DOM node operation during code compilation, so that DOM nodes can be updated quickly and efficiently when the component state changes. According to the statistics of JS framework benchmark, svelte performs better than react and Vue on some large lists.

What is svelte?

Svelte is a compiled framework written by rich Harris, the author of rollupjs. Students who have not known rollupjs can go to its official website to learn about it. It is actually a package tool similar to webpack. The svelte framework has the following features:

  • Similar to react, Vue and other modern web frameworks, it allows developers to quickly develop web applications with smooth user experience.
  • Not usedVirtual DOMIs not a runtime library.
  • Based on the concept of compiler as framework, your application will be converted into native DOM operation when compiling.
  • By default, it supports CSS scope functions similar to CSS modules, so that you can avoid CSS style conflicts.
  • CSS animation is supported natively.
  • It is extremely easy to manage the component state and reduce the boilerplate less of developers.
  • Reactive statement is supported.
  • It is very easy to apply global state management. The framework itself has its own global state, similar to Redux of react and vuex of Vue.
  • Support context to avoid props drilling of components.

The biggest difference between svelte and Vue and react is that it has many other useful functions besides managing the state of components and tracking their rendering. For example, it supports CSS scope and CSS animation natively. If you use react or Vue, you need to introduce a third-party library to achieve the same function, and the introduction of third-party dependency will increase the cost of learning and maintenance for developers.

Building a bookstore application with svelte

Next, we will build a simple Bookstore application bookshop based on svelte framework from scratch. Through this demo, we hope you can understand some basic concepts of svelte and master its basic usage, and can use svelte to build more complex applications.

Application function

The bookstore application supports the following functions:

  • Administrator enters new books
  • Show book list of bookstores
  • Add books to cart
  • Display the data information of shopping cart

Technical requirements for learners

  • Master the basic usage of HTML, CSS and JavaScript
  • Experience with react or Vue is preferred

The source code of the project can be found in my GitHub repository.

Project construction

First, create a new project folder in our local development environment

mkdir svelte-bookshop

Then we use svelte’s official scaffold to initialize our application

npx degit sveltejs/template svelte-bookshop
cd svelte-bookshop

yarn
yarn dev

Degit will directly copy the project file above GitHub to a local folder. The GitHub address of the svelte / tempalt template project used here is this. After the above command runs successfully, access the http://localhost : 5000 you will see the following interface:
You haven't heard of sveltejs yet?
The interface is very simple. It shows a hello world. Then let’s take a look at the generated project directory structure
You haven't heard of sveltejs yet?
The generated code mainly includes the following file directory structure:

  • rollup.config.js This is the rollup configuration file, similar to webpack.config.js , which specifies that the entry file of the project is Src/ main.js 。
  • SRC folder, this folder is used to store our project source code, now there is only one main entry file of the project main.js And a component file App.svelte 。
  • Public folder, which is used to store static files of the project( index.html , global.css and favicon.png )And rollup to generate static files (under the build folder bundle.js and bundle.css And their respective source maps).

Let’s take a look at the contents of the files under the SRC folder

src/App.svelte

<script>
    export let name;
</script>

<main>
    <h1>Hello {name}!</h1>
    <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
    main {
        text-align: center;
        padding: 1em;
        max-width: 240px;
        margin: 0 auto;
    }

    h1 {
        color: #ff3e00;
        text-transform: uppercase;
        font-size: 4em;
        font-weight: 100;
    }

    @media (min-width: 640px) {
        main {
            max-width: none;
        }
    }
</style>

This file defines an svelte component called app, which should be noted here App.svelte The name of the component is not defined in the file,The name of a component is determined by its file nameThe filenames of svelte components end with. SvelteA component file usually contains the following three parts:

  • < script > tagAny JavaScript code associated with a component can be placed here, such as a component’s state definition or some asynchronous Ajax request. Here it is App.svelte The file does not define the local component state, but defines and exports a name variable. For the current component, the variable sprevels is specified as an external variable. This method is quite different from using props as the first parameter of a component in react. You may not be used to it at first, but if you get used to it later, you may fall in love with this method.
  • < style > labelThe CSS code associated with the component will be placed here. Note that CSS is locally scoped, that is to say App.svelte The style of the H1 tag in the app component is only valid for the H1 tag in the app component, but it is invalid for the H1 tag of other project nodes including the child nodes of this component. You can use the browser’s debugging tool to see the actual style of the H1 tag

You haven't heard of sveltejs yet?As can be seen from the figure above, svelte uses some random hash values to distinguish the styles of components from those of other components when generating code.

  • HTML tags for components。 The HTML tag of the component can be written directly in the file. For example, the HTML part of the app component is:
<main>
    <h1>Hello {name}!</h1>
    <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

The outermost layer of the app component is a main tag. There are an H1 tag and a p tag in the main tag, of which the H1 tag is aHello String plus an insertion string wrapped with curly brackets. The writing method in react JSX should beHello ${name}They all indicate that the string at this position is the content of the variable name. As for the name variable, it is the external parameter defined by export above.

Generally speaking, svelte will put all the JavaScript, CSS and HTML code related to components in the same file, which is a bit like Vue, but it has less template code than Vue.

src/main.js

import App from './App.svelte';

const app = new App({
    target: document.body,
    props: {
        name: 'world'
    }
});

export default app;

The content of this file is very simple, that is, mount the app component just defined to the target node body, and provide the app component with a value ofworldThe name parameter of. The function of this code is similar to that in react ReactDOM.render The function is the same.

Next, let’s take a look at what the generated static code looks like.

public/build/bundle.js

Let’s look at the generated JavaScript main file bundle.js Due to the large size of the original file, I only intercepted the key part:

/* src/App.svelte generated by Svelte v3.16.4 */

const file = "src/App.svelte";

function create_fragment(ctx) {
  let main;
  let h1;
  let t0;
  let t1;
  let t2;
  let t3;
  let p;
  let t4;
  let a;
  let t6;

  const block = {
    c: function create() {
      main = element("main");
      h1 = element("h1");
      t0 = text("Hello ");
      t1 = text(/*name*/ ctx[0]);
      t2 = text("!");
      t3 = space();
      p = element("p");
      t4 = text("Visit the ");
      a = element("a");
      a.textContent = "Svelte tutorial";
      t6 = text(" to learn how to build Svelte apps.");
      attr_dev(h1, "class", "svelte-1tky8bj");
      add_location(h1, file, 5, 1, 46);
      attr_dev(a, "href", "https://svelte.dev/tutorial");
      add_location(a, file, 6, 14, 83);
      add_location(p, file, 6, 1, 70);
      attr_dev(main, "class", "svelte-1tky8bj");
      add_location(main, file, 4, 0, 38);
    },
    l: function claim(nodes) {
      throw new Error("options.hydrate only works if the component was compiled with the `hydratable: true` option");
    },
    m: function mount(target, anchor) {
      insert_dev(target, main, anchor);
      append_dev(main, h1);
      append_dev(h1, t0);
      append_dev(h1, t1);
      append_dev(h1, t2);
      append_dev(main, t3);
      append_dev(main, p);
      append_dev(p, t4);
      append_dev(p, a);
      append_dev(p, t6);
    },
    p: function update(ctx, dirty) {
      if (dirty[0] & /*name*/ 1) set_data_dev(t1, /*name*/ ctx[0]);
    },
    i: noop,
    o: noop,
    d: function destroy(detaching) {
      if (detaching) detach_dev(main);
    }
  };

  dispatch_dev("SvelteRegisterBlock", {
    block,
    id: create_fragment.name,
    type: "component",
    source: "",
    ctx
  });

  return block;
}

This code corresponds to the app component we just defined,create_fragmentMethod takes a context objectctxParameter and returns a block object representing the component.

block

This object mainly contains the following four important methodsc(create),m(mount),p(update) andd(destroy)。

c(create)

function create() {
  main = element("main");
  h1 = element("h1");
  t0 = text("Hello ");
  t1 = text(/*name*/ ctx[0]);
  t2 = text("!");
  t3 = space();
  p = element("p");
  t4 = text("Visit the ");
  a = element("a");
  a.textContent = "Svelte tutorial";
  t6 = text(" to learn how to build Svelte apps.");
  attr_dev(h1, "class", "svelte-1tky8bj");
  add_location(h1, file, 5, 1, 46);
  attr_dev(a, "href", "https://svelte.dev/tutorial");
  add_location(a, file, 6, 14, 83);
  add_location(p, file, 6, 1, 70);
  attr_dev(main, "class", "svelte-1tky8bj");
  add_location(main, file, 4, 0, 38);
}

The function is to create some native DOM nodes related to app components and add some metadata to them.

m(mount)

function mount(target, anchor) {
  insert_dev(target, main, anchor);
  append_dev(main, h1);
  append_dev(h1, t0);
  append_dev(h1, t1);
  append_dev(h1, t2);
  append_dev(main, t3);
  append_dev(main, p);
  append_dev(p, t4);
  append_dev(p, a);
  append_dev(p, t6);
}

The function of this function is to mount the DOM nodes generated by the C function.

p(update)

function update(ctx, dirty) {
  if (dirty[0] & /*name*/ 1) set_data_dev(t1, /*name*/ ctx[0]);
}

The P function will update the properties of the corresponding DOM node when the CTX context is updated. When the context changes, check whether the variable name has changed. If so, update the DOM node.

d(destroy)

function destroy(detaching) {
  if (detaching) detach_dev(main);
}

The D function is used to delete app components.

After reading the code generated by svelte, I think you should have a deeper understanding of the compiler as framework concepts I mentioned at the beginning of the article. The difference between svelte and react (similar to Vue) is that,After packaging, the react application still retains React.createElement , setstate and other framework functions. After svelte is compiled, the framework code will be converted to the code that operates the native DOM node.

After understanding the organizational structure of the project, let’s start to formally build the bookstore bookshop application.

Component definition

HTML markup

First of all, let’s create a card component to display the book’s specific information, and create a new one under the SRC folder BookCard.svelte File, which defines the HTML markup of the card component:

// src/BookCard.svelte
<div>
  <h1>title</h1>
  <div>price</div>
  <div>description</div>
  < button > add to cart < / button >
</div>

And then in the App.svelte The bookcard component is used in the component

// src/App.svelte
<script>
  import BookCard from "./BookCard.svelte";
</script>

<style>
 ...
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <BookCard />
  </section>
</main>

The method of using custom components is very simple: first import the newly defined component bookcard in the script tag, and then write the component in the HTML markup of APP component, with the same syntax as JSX.At this time, check the content of the page:
You haven't heard of sveltejs yet?

CSS

Although the bookcard component has come out, we have to define some CSS to make it look better

// src/BookCard.svelte
<style>
  .card {
    text-align: left;
    border-radius: 5px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
    padding: 10px;
  }

  h1 {
    font-size: 20px;
  }

  h2 {
    font-size: 15px;
    color: #999;
  }

  button {
    background-color: #ff3e00;
    color: white;
    border-radius: 5px;
    cursor: pointer;
    border: none;
  }
</style>

<div class="card">
  <h1>title</h1>
  <h2>price</h2>
  <p>description</p>
  < button > add to cart < / button >
</div>

The way to define a style for a component is to create a new style label, and then write the style related to the component in this label. Note that the style here is only valid for the elements in the component, and will not affect the styles of other components. After adding styles, the interface should look like this:
You haven't heard of sveltejs yet?

Props definition

The specific information of the book should be specified by the incoming props.The props of the svelte component should be indicated by export, and the specified props variable can be directly used by the component

// src/BookCard.svelte
<script>
  export let title;
  export let price;
  export let description;
</script>

<style>
...
</style>

<div class="card">
  <h1>title</h1>
  <h2>price</h2>
  <p>description</p>
  < button > add to cart < / button >
</div>

Variable usage

The variables defined and introduced can be directly used in the HTML markup of the component. The specific usage is to use curly braces to refer to the variable in the markup. For specific code:

// src/BookCard.svelte
<script>
  export let title;
  export let price;
  export let description;
</script>

<style>
...
</style>

<div class="card">
  <h1>{title}</h1>
  <h2>${price}</h2>
  <p>{description}</p>
  < button > add to cart < / button >
</div>

Component parameter transfer

Then, in the parent component app, pass the parameters required by bookcard to the component:

// src/App.svelte
<script>
  ...
  Let Title: "JavaScript advanced programming";
  let price = 99.0;
  Let description = "let's learn JavaScript together";
</script>

<style>
  ...
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <BookCard title={title} price={price} description={description} />
  </section>
</main>

At this time, the content of the book card should be the parameter passed in:
You haven't heard of sveltejs yet?
For component parameter passing, svelte also provides the following more convenient writing methods:

// src/App.svelte
<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <BookCard {title} {price} {description} />
  </section>
</main>

Input book information

As a bookstore, administrators should be able to enter new books, so we add a simple form to app components to let users enter data:

// src/App.svelte
<script>
  ...
</script>

<style>
  ....
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <h2>Add new book</h2>
    <label for="title">Title</label>
    <input type="text" id="title" value={title} />
    <label for="price">Price</label>
    <input type="number" id="price" value={price} />
    <label for="description">Description</label>
    <textarea rows="3" id="description" value={description} />
  </section>
  <section>
    <BookCard {title} {price} {description} />
  </section>
</main>

We create new input tags for app components, and specify the values of these input tags as the variables we defined previously. At this time, we try to change the contents of the input box:
You haven't heard of sveltejs yet?
Although the initial value of the input box is the value corresponding to the variable, the value of the variable will not change with the change of the value of the input box, that is, their values are not “bound”. To achieve bidirectional data binding, we can add a listening event to the input box.

Event binding

We can add an event listener to the DOM using the on keyword plus the event nameThe following code will listen to theinputevent:

<script>
  ...
  Let Title: "JavaScript advanced programming";
  ...

  function handleTitleChange(event) {
    title = event.target.value;
  }
</script>

<style>
  ...
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <h2>Add new book</h2>
    <label for="title">Title</label>
    <input type="text" id="title" value={title} on:input={handleTitleChange} />
    ...
  </section>
</main>

At this time, if we change the input value, we will find that the content in the card has also changed, indicating that we have successfully changedtitleValue of variable:
You haven't heard of sveltejs yet?

Automatic data bidirectional binding

However, if you have to manually add an event listener for each input tag, our code will have a lot of template code. To solve this problem,Svelte allows us to bind two-way data directly with the bind keyword and the attribute to be bound

// src/App.svelte
<script>
  ...
  Let Title: "JavaScript advanced programming";
  let price = 99.0;
  Let description = "let's learn JavaScript together";
</script>

<style>
  ...
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <h2>Add new book</h2>
    <label for="title">Title</label>
    <input type="text" id="title" bind:value={title} />
    <label for="price">Price</label>
    <input type="number" id="price" bind:value={price} />
    <label for="description">Description</label>
    <textarea rows="3" id="description" bind:value={description} />
  </section>
  ...
</main>

In this case, we can remove the initial value of each variable

// src/App.svelte
<script>
  let title = "";
  let price = 0;
  let description = "";
</script>

At this time, the input box and all variables on our page are “bound”
You haven't heard of sveltejs yet?

Show book list

Our bookstore should have more than one book. We should use an array to store all the books

// src/App.svelte
<script>
  ...
  let books = [];
  ...
</script>

Then we add a submit button to the newly added form. After the user fills in the book information, click submit to create a new book object, which will be added to the books list

<script>
  ...
  let books = [];

  function handleAddBook() {
    books = books.concat({ title, price, description });
    title = "";
    price = 0;
    description = "";
  }
  ...
</script>

<style>
  ...
  button {
    background-color: #ff3e00;
    color: white;
    border-radius: 5px;
    cursor: pointer;
    border: none;
  }
  ...
</style>

<main>
  <h1>Welcome to my online bookstore!</h1>
  <section>
    <h2>Add new book</h2>
    <label for="title">Title</label>
    <input type="text" id="title" bind:value={title} />
    <label for="price">Price</label>
    <input type="number" id="price" bind:value={price} />
    <label for="description">Description</label>
    <textarea rows="3" id="description" bind:value={description} />
    <div>
      <button on:click={handleAddBook}>add book</button>
    </div>
  </section>
  ...
</main>

Display list data

We can use each syntax block to display the data of books list

// src/App.svelte
<script>
  ....

  let books = [];

  function handleAddBook() {
    books = books.concat({ title, price, description });
    title = "";
    price = 0;
    description = "";
  }
</script>

<main>
  ...
  <section>
    {#each books as book}
      <BookCard
        title={book.title}
        price={book.price}
        description={book.description} />
    {/each}
  </section>
</main>

You can also deconstruct the contents of the recursive object directly when each block is defined, the above code changes to:

// src/App.svelte
  ...
  <section>
    {#each books as { title, price, description }}
      <BookCard {title} {price} {description} />
    {/each}
  </section>
  ...

After the code is changed, you can enter the new book and display the list of books on your page
You haven't heard of sveltejs yet?

Shopping cart function

First, we add a click event to the button of the bookcard component: when the user clicks the book card button, the book will be added to the shopping cart. To achieve this effect, we can define ahandleAddBookThis parameter is provided by external components,handleAddBookThe function is called when the user clicks the bookcard button and adds the book to the shopping cart. The code is as follows:

// src/BookCard.svelte
<script>
  ...
  export let handleAddToCart;
</script>

<style>
  ...
</style>

<div class="card">
  <h1>{title}</h1>
  <h2>${price}</h2>
  <p>{description}</p>
  < button on: Click = {() = > handleaddtocart (title)} > add to cart
</div>
// src/App.svelte
<script>
  ...
  let booksInCart = [];

  function handleAddToCart(title) {
    let bookNeededToBeAdded = books.find(book => book.title == title);
    booksInCart = booksInCart.concat(bookNeededToBeAdded);
  }
</script>

<style>
  ...
</style>

<main>
  ...
  <section>
    <h2>Shopping cart</h2>
    {#each booksInCart as { title, price }}
      < div > Name: {Title}, price: {price} < / div >
    {/each}
  </section>
  <section>
    <h2>Book list</h2>
    {#each books as { title, price, description }}
      <BookCard {title} {price} {description} {handleAddToCart} />
    {/each}
  </section>
</main>

Then we can see our shopping cart:
You haven't heard of sveltejs yet?

Conditional judgment

Svelte can display different contents according to different conditions with if syntax blocksWhen the shopping cart is empty, we can show the user an empty status:

// src/App.svelte
...
<section>
  <h2>Shopping cart</h2>
  {#if booksInCart.length === 0}
    <p>The shopping cart is empty~</p>
  {:else}
    {#each booksInCart as { title, price }}
      < div > Name: {Title}, price: {price} < / div >
    {/each}
  {/if}
</section>
...

At this time, the interface becomes:
You haven't heard of sveltejs yet?

Show cart statistics

We also add a function for the bookstore to help users count the books in the shopping cart, which can display the total number and total amount of books in the shopping cart. The code is as follows:

// src/App.svelte
<script>
  ...
  let booksInCart = [];

  let booksNumInCart = booksInCart.length;
  let totalCheckoutPrice = booksInCart.reduce(
    (sum, book) => sum + book.price,
    0
  );
  ...
</script>

...
<section>
  <h2>Shopping cart</h2>
  < div > total number of books: {books numincart} < / div >
  < div > order amount: {totalcheckoutprice} < / div >
  ...
</section>
...

At this time, we found that the statistical data did not change when the data of shopping cart changed
You haven't heard of sveltejs yet?
The reason the data doesn’t change is that we don’t change it manually every time we add books to the shopping cartbooksNumInCartandtotalCheckoutPriceValue of. However, if you need to manually maintain statistics when the shopping cart data changes, the code can get ugly.

Definition of reaction

For this case, svelte providesDefinition of reaction(reactive assignment),The specific method is to use$Symbols define variables instead of lets, here is the code:

<script>
  ...
  let booksInCart = [];

  $: booksNumInCart = booksInCart.length;
  $: totalCheckoutPrice = booksInCart.reduce(
    (sum, book) => sum + book.price,
    0
  );
  ...
</script>

So whenbooksInCartWhen this data changes,booksNumInCartandtotalCheckoutPriceThese two variables are automatically recalculated.
At this time, if we operate the interface again, we will find that the statistical data will automatically change with the change of shopping cart data
You haven't heard of sveltejs yet?

Package release

Finally, let’s package the bookshop application we just wrote. Run the following command under the root directory to package the code:

yarn build

After packaging, check the size of the generated file:

➜  build git:(master) ls -lh
total 152
-rw-r--r--  1 sean  staff   659B 12 17 14:17 bundle.css
-rw-r--r--  1 sean  staff   3.9K 12 17 14:17 bundle.css.map
-rw-r--r--  1 sean  staff   7.6K 12 17 14:17 bundle.js
-rw-r--r--  1 sean  staff    57K 12 17 14:17 bundle.js.map

You can see bundle.js It’s only less than 8K, and the react framework is estimated to be 100k +. From this point of view, the svelte framework does reduce a lot of generated code.

summary

Our bookshop system has probably realized these functions. Now let’s summarize the basic knowledge of svelte framework covered in the development project:

  • Component definition
  • Using variables – using variables
  • Props definition and passing
  • Event listening
  • Data binding
  • Condition – if condition
  • List data display – each block

In fact, the svelte framework has many useful features that I did not mention, such as:

  • Event Forwarding
  • Life cycle functions
  • Global state management stores
  • Context management – Context
  • CSS animation – CSS animation

Due to the limitation of the length of this article, I have not covered all the attributes of svelte here. You can take a look at the official tutorial of svelte.

My personal views on the svelte framework

In my opinion, due to various problems of virtual DOM, compiler as framework should be a trend in the development of front-end framework. Although the functions of svelte are very good at present, I think it has the following problems:

  • Scalability – scalability. Although the runtime provided by react and Vue frameworks will increase the bundle.js But as the project gets bigger and bigger, the runtime of the framework bundle.js On the contrary, because the encapsulation of svelte generated code is not as good as react and Vue, will it accumulate a lot of duplicate code in large projects? At this time, we have to consider whether there is a threshold value for svelte generated code that is greater than the code generated by react and Vue. There is no specific answer to this question. We can only give the answer when we practice it. If you are interested, we can have a look at the author’s discussion on GitHub.
  • Ecosystem – ecology. As a recently popular framework, svelte’s ecology is far less than react and Vue, which have been popular for so many years. This is why I think svelte can not shake the status of react and Vue. But will Svelte usher in an ecological explosion because of its advanced nature? We can wait and see.

However, one thing is certain that svelte will shine in some embedded operating systems with poor performance because the code generated in some uncomplicated projects is much smaller than react, Vue and angular.

Learn svelte useful links

  • Speech by retreating
  • Svelte website
  • Svelte GitHub warehouse

Keep an eye on my technology trends

I’m an aggressive green onion. Now I’m a team leader in an e-commerce company. Pay attention to me and me to become a full stack engineer on my own!

Team blog address: space Fe blogs

Focus on my official account and get my latest technology push!
You haven't heard of sveltejs yet?