Kalan's Blog

Current Theme light

2022 年值得學習 Svelte 的四個理由 | Svelte 系列文

1. Continuous Increase in Popularity

According to the State of JS survey, Svelte was included as an option in the questionnaire in 2019, and at that time it had a satisfaction rate of 88% (compared to React's 89% and Vue's 87%). This year, it has become the top-rated front-end framework with a satisfaction rate of 89%.

Screenshot_2021-02-09 State of JS 2020 Front-end Frameworks

Additionally, its usage rate, which was 8% in 2019, has risen to 15% in 2020, making it the fourth most popular front-end framework. This indicates that more and more people are paying attention to this front-end framework.

Screenshot_2021-02-09 State of JS 2020 Front-end Frameworks(1)

2. Low Entry Barrier, Easy to Get Started

Svelte's syntax is almost entirely compatible with HTML. Additionally, template syntax such as {#if} and {#each} is easy to understand if you have experience with template engines like .ejs or .pug. The design goal of Svelte's syntax is to reduce cognitive load, so beginners can quickly get started once they grasp the basic concepts. A Svelte component looks like this:

<script>
  export let prop; // declared like this
  let count = 1; // variables are declared like this
  onMount(() => { // lifecycle method
    count++; // changing the variable triggers component update
  })
</script>

<style>
  p { font-size: 14px }
</style>

<!-- variables are wrapped in {} -->
<p>{count}</p> 

<!-- attribute passing -->
<Component count={count} />

You don't need to learn additional concepts like hooks to understand the appearance of components easily. As for styling, Svelte adds a hash during compilation, so you don't have to worry about CSS class name conflicts. All of this is handled within Svelte's implementation, which means there is no need for additional loaders (e.g., css-module) to handle it.

For those who primarily focus on backend development but occasionally need to develop frontend pages, Svelte is a very easy-to-use and efficient tool for quick development.

3. Small Bundle Size

Compared to React or Vue, Svelte compiles the code before generating the final output. This allows for some compilation optimizations and dependency tracking mechanisms. Interested readers can refer to the article "Virual DOM is pure overhead" written by the author, which mentions that in order to achieve declarative effects without directly manipulating the DOM API, some performance trade-offs are necessary. For example, React uses a Virtual DOM and diffing mechanism. To keep the cost of diffing low and compatible across multiple platforms, React needs a lightweight mechanism to describe the render tree, which is the Virtual DOM.

In large applications, if performance issues arise, React provides various optimization mechanisms such as useMemo and shouldComponentUpdate APIs for developers to fine-tune performance.

Svelte, on the other hand, does not have the concept of Virtual DOM, and its crucial dependency tracking mechanism is already analyzed during the static phase. Therefore, the runtime bundle size of Svelte is much smaller than that of React and Vue. This means that in small to medium-sized applications, Svelte often has a smaller bundle size and better performance.

4. Built-in Transition and Animation Mechanisms

Svelte has built-in transition functionality that integrates well with common development scenarios. In fact, Svelte even has built-in transition mechanisms. You can use the transition directive to achieve transition effects, and Svelte will determine when to execute the transition (entering or leaving) for you.

In Svelte, you can write code like this:

<script>
  import { scale } from "svelte/transition";
  import { onMount } from "svelte";

  let toggle = false;

  onMount(() => {
    setInterval(() => {
      toggle = !toggle;
    }, 2000);
  });
</script>

<main>
  {#if toggle}
    <h1 transition:scale>Hello World</h1>
  {/if}
</main>

When {#if toggle} is true, the h1 element will be rendered (entering), and when it is false, it will be removed (leaving). By adding transition:scale, Svelte will perform the transition at the appropriate time.

In React, you usually need to use react-transition-group, otherwise writing toggle && <Component /> would directly unmount the component when toggle is false, preventing the transition from occurring smoothly. Alternatively, you can use react-spring to achieve more advanced animation interactions.

Vue developers might think this is nothing special since Vue also has a built-in transition mechanism, and it performs the corresponding transition based on the v-if condition. However, the difference is that in Vue, you have to define class names and transition implementations in CSS, whereas in Svelte, you can do it declaratively without defining additional class names in CSS.

"Anyway, it's definitely using JavaScript to directly modify inline styles, which is extremely inefficient."

In fact, Svelte dynamically generates CSS keyframes. The animation's source code is here:

function go() {
  const {
    delay = 0,
    duration = 300,
    easing = linear,
    tick = noop,
    css
  } = config || null_transition;

  if (css) animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
  ...
}

The create_rule function is the core of the entire transition mechanism. Its implementation is based on stylesheet.insertRule. For example, if you declare a transition like this:

function myTransition(node) {
  return {
    css: t => `
      transform: scale(${1 - t});
    `;
  }
}

It will actually generate an animation keyframe (using insertRule):

@keyframes svelte_hash_animation_name {
  0% {
    transform: scale(0);
  }
  
  10% {
    transform: scale(0.1);
  }
  
  20% {
    transform: scale(0.2);
  }
  
  30% {
    transform: scale(0.3);
  }
  ...
}

Then it will be added to the DOM node that needs to perform the animation. This avoids modifying inline styles for every frame, which would consume unnecessary performance.

Easy Implementation of Crossfade and FLIP Effects

It's easier to understand with an example. Please click the button on the page to see the actual effect:

When you click, the tags will transition from their current position to the target position. This effect can be easily achieved with Svelte. Additionally, when you click a tag, you will notice that other tags also transition accordingly. This makes the interaction smoother. This technique is called FLIP, and it is also implemented in Svelte.

Disadvantages

After discussing the advantages, let's now talk about the disadvantages based on personal experience.

1. Doing Too Much at Compile Time

For example, Svelte performs dependency tracking during the static phase and sometimes generates code that you may want to debug to see if there are any strange parts that need adjustment. This can make debugging more challenging.

Additionally, for developers familiar with HTML, this may not be an issue. However, for beginners, Svelte components may look similar to HTML but have subtle differences, such as the {} syntax and reactive variables, which can cause confusion.

Svelte's requirement for pre-compilation also means that it cannot be used like Vue, where you can simply import a library in the <script> tag and start using it. Instead, you need tools like Vite or webpack to run Svelte.

2. Must Adhere to Svelte's Component Format

To create a Svelte component, you must follow Svelte's component format. In contrast, in React, all components are JavaScript files, so you can write them using any valid JavaScript code.

3. Relatively Fewer Resources and Incomplete Ecosystem Compared to Other Front-end Frameworks

Although there has been an increase in Svelte resources recently, the majority of them are in English, and there is still a relatively smaller amount of Chinese resources available. This makes it more challenging to find answers to questions, and the solution ecosystem is not as complete as with other front-end frameworks. This can only be resolved over time or by creating more Svelte-related resources together!

4. Lower Adoption Rate

For most companies, the adoption rate of Svelte is still relatively low, so it may not be the best choice for job seekers.

Conclusion

Svelte has a distinct positioning compared to other front-end frameworks. Its concise syntax, compilation-based approach, "write less code" philosophy, and small bundle size have gained attention in recent years. I personally appreciate this diversity. Although it may not be everyone's cup of tea, having clashes of ideas can bring more progress and even inspire new ideas. As we approach the new year in 2021, it might be worth temporarily setting aside the familiar front-end frameworks and giving Svelte, the top-rated framework in terms of satisfaction in 2020, a try!

If you're interested in Svelte, you can refer to some of the articles I've written in the past here.

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee