Why Svelte Beats React & Vue: Compilation, Reactivity, and Ecosystem Explained
This article introduces Svelte, explains its compile‑time approach versus runtime frameworks, compares code size and performance with React and Vue, details its reactivity model, compiler and runtime internals, explores the surrounding ecosystem, and shows how to build web components and assess its suitability for projects.
大厂技术坚持周更精选文
简介
Svelte is a tool for building web applications, similar to JavaScript frameworks like React and Vue, aiming to make interactive UI development easier.
The key difference is that Svelte transforms your app into optimal JavaScript at build/compile time rather than interpreting code at runtime , eliminating framework performance overhead and initial load penalties.
You can build an entire app with Svelte, gradually integrate it into existing code, or ship components as independent packages without the extra bloat of traditional frameworks.
特点
代码简洁
Example: input a value and show it in a modal. The Svelte code is far shorter than equivalent React or Vue implementations.
Using Svelte:
<script>
let animal = 'dog';
const showModal = () => {
alert(`My favorite animal is ${animal}`);
};
</script>
<input type="text" bind:value={animal} />
<button on:click={showModal}>弹出</button>React:
import React, { useState } from 'react';
export default function App() {
const [animal, setAnimal] = useState('dog');
const showModal = () => {
alert(`My favorite animal is ${animal}`);
};
return (
<>
<input type="text" value={animal} onChange={() => { setAnimal(animal); }} />
<button onClick={showModal}>弹出</button>
</>
);
}Vue:
<template>
<div>
<input type="text" v-model="animal" />
<button @click="showModal">弹出</button>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const animal = ref('dog');
const showModal = () => {
alert(`My favorite animal is ${animal.value}`);
};
return { animal, showModal };
},
});
</script>无虚拟 DOM
Svelte compiles code into small, framework‑free JavaScript, resulting in fast startup and runtime performance.
性能更好
Although many hear that virtual DOM is fast, Svelte achieves better performance by eliminating the virtual DOM and updating the real DOM directly based on compile‑time analysis.
React and Vue use virtual DOM mainly for maintainability, not raw speed. They optimize list rendering by marking items with keys, but Svelte performs similar optimizations at compile time, resulting in even higher efficiency.
When you manually mark list items in real DOM, you can skip the virtual‑DOM diff step and achieve higher performance, which is exactly what Svelte does by pre‑computing the DOM‑data mapping.
体积更小?
React and Vue include a runtime in the bundle, while Svelte reduces runtime code through static compilation.
According to npm trends, min‑zipped sizes are 42.2 KB (React), 22.9 KB (Vue), and 1.6 KB (Svelte), demonstrating Svelte's compactness.
However, for many components the size advantage diminishes because Svelte’s compiled component code can be larger per component than Vue/React. If each component size is a and React/Vue component size is b, total size scales as a·n for Svelte versus S + b·n for the others; when a > b, Svelte’s advantage fades as n grows.
真正的 reactivity
Svelte adds reactivity directly to JavaScript without needing external state‑management libraries. The following sections decode its reactivity implementation.
发展趋势
Svelte was created by Rich Harris (author of Rollup) and open‑sourced in 2016. It gained wider attention in 2019.
GitHub stars: 49.9 k. Weekly npm downloads: around 150 k.
Although still behind React, Vue, and Angular in stars and downloads, user satisfaction and interest have been top‑ranked for the past two years.
源码解读
Svelte's source consists of a compiler and a runtime. The compiler transforms .svelte files into JavaScript components; the runtime provides helper functions for DOM manipulation.
compiler
The compiler works in two phases: parse and compile .
parse
Parse reads .svelte files and builds an AST containing html, css, instance, and module parts. tag: HTML elements, svelte:head, svelte:options, etc. mustache: expressions inside {}, including control flow and {@html}. text: static text nodes.
The resulting AST separates script (instance) code, which holds reactive variables, from module‑level code.
compile
Compile converts the AST into a Component object. The render_dom step uses a code‑generator to emit JavaScript that creates, mounts, updates, and destroys DOM nodes.
runtime
Example: a button that increments a counter.
<script>
let count = 0;
const addCount = () => {
count += 1;
};
</script>
<div>
<button on:click={addCount}>增加</button>
<p>count is: {count}</p>
</div>Compiled output includes a create_fragment function (handling create, mount, update, destroy) and an instance function that returns reactive state and methods.
The runtime imports helpers such as append, detach, element, insert, listen from svelte/internal, which are thin wrappers around native DOM operations.
create_fragment
Defines methods c (create), m (mount), p (update), d (destroy), etc., to manage the component lifecycle.
instance
Returns an array of component state and methods, stored in $$.ctx. When a reactive variable changes, $$invalidate marks it dirty.
脏检测
make_dirtyadds the component to a dirty list and schedules an update. schedule_update defers flush via a resolved promise. flush iterates over dirty components, calling their update hook, which runs the fragment’s p method to patch the DOM.
Dirty flags are stored as 32‑bit integers, using bitwise operations to efficiently track which indices need updating.
整体流程
周边生态
状态管理
Svelte provides a built‑in store for state management, eliminating the need for external libraries.
路由
svelte-routing – 1.4k stars, API similar to react‑router‑dom.
svelte-spa-router – 886 stars, resembles vue‑router.
SSR
sveltekit – official SSR framework with routing, TypeScript, SCSS, serverless support, and Vite bundling.
Sapper – predecessor, no longer actively maintained.
跨平台
Svelte can be used with electron for desktop apps and has a community svelte-native project for native mobile, though official support for mini‑programs is lacking.
组件库
svelte-material-ui – Google‑style UI components.
carbon-components-svelte – IBM design system.
smelte – alternative Material design.
测试工具
Community testing library: svelte-testing-library .
使用 Svelte 构建 Web Component
Svelte’s small runtime makes it ideal for building web components without the heavy bundle overhead of React or Vue.
配置
Create a component template: npx degit sveltejs/component-template custom-test-button Adjust package.json to set the package name and entry points.
Configure rollup.config.js with customElement: true.
Add component code using <svelte:options tag="custom-test-button"/> and define props.
Build with npm run build to produce index.js.
使用
HTML: include the built script and use <custom-test-button> with attributes.
Vue: load the script and embed the custom element in a Vue template.
React: similar approach (not detailed).
总结
Svelte introduces a novel compile‑time reactivity model that yields small bundles and fast runtime performance. Its ecosystem is still maturing, and large‑scale projects may see diminishing size benefits, but for simple pages, activity pages, and static sites it is an excellent choice. The syntax is concise and Vue‑like, making the learning curve shallow.
Explore Svelte to broaden your front‑end toolkit.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
