Lesson 01-Svelte Basics Introduction

Introduction to Svelte

Svelte is a JavaScript frontend framework focused on building user interfaces. Unlike frameworks like React and Vue, Svelte’s primary characteristic is its compile-time code transformation, rather than relying on runtime virtual DOM diffing and updates. This results in smaller, faster Svelte applications upon deployment, as they incur no framework runtime overhead.

History and Features of Svelte

History

Svelte was initially developed by Rich Harris, who released its first version in 2016. Harris’s primary goal in designing Svelte was to create a framework that delivers optimal performance by eliminating framework runtime code during the build phase.

Features

  • Code Elimination: Svelte removes all unnecessary framework code during the build process, leaving only pure JavaScript and DOM operations. This results in smaller bundle sizes and faster load times.
  • Reactive Updates: Svelte uses a “dirty checking” mechanism to detect changes in component state, updating only the parts that actually need to be re-rendered.
  • Simple API and Syntax: Svelte offers an intuitive and easy-to-understand API, enabling developers to quickly get started and build complex user interfaces.
  • Template Syntax: Svelte supports an HTML-like template syntax, allowing developers to write code close to native HTML while leveraging the framework’s reactive capabilities.

Comparison with React, Vue, Angular, and Other Frameworks

  • React: React uses a virtual DOM and diffing algorithm to determine which parts need re-rendering, incurring additional computational overhead at runtime. In contrast, Svelte determines updates during the build phase, making it more lightweight at runtime.
  • Vue: Vue also supports reactive updates but maintains a virtual DOM at runtime. While Vue’s syntax and API are easy to learn, Svelte achieves better performance through deeper code optimizations.
  • Angular: Angular is a comprehensive MVC framework with a rich feature set, including dependency injection and a powerful templating system. However, its bundle size is typically much larger than Svelte’s due to extensive runtime framework code.

How Svelte Works: An Overview

Svelte’s core lies in its compiler. When building a Svelte application, the compiler analyzes your components, identifies reactive parts, and generates optimized JavaScript code. This process includes:

  • Static Hoisting: Elevates invariant parts to the outermost scope to reduce redundant DOM access.
  • Code Generation: Produces specific update logic based on component state changes, avoiding generic update strategies.
  • Dependency Tracking: Automatically tracks dependencies within components, ensuring updates are triggered only when relevant state changes.

Svelte Installation and Usage

Installing Node.js and npm

  • Download Node.js: Visit the Node.js official website to download the latest stable version. The Node.js installer includes npm.
  • Install Node.js: Run the downloaded installer and follow the prompts to complete the installation.
  • Verify Installation: Open a terminal and run the following commands to confirm that Node.js and npm are installed correctly:
node -v
npm -v

Using degit to Quickly Create a Svelte Project

Svelte provides various scaffolding tools to help you set up projects quickly. degit is a particularly convenient tool for cloning templates from GitHub repositories to your local machine.

Install degit Globally: Run the following command in your terminal:

npm install -g degit

Create a Svelte Project: Use degit to create a project from Svelte’s official template. For example, to create a project named my-svelte-app:

degit sveltejs/template my-svelte-app
cd my-svelte-app

Install Project Dependencies: Navigate to the project directory and install the required dependencies:

npm install

Start the Development Server: After installing dependencies, start the development server with:

npm run dev

The browser will automatically open and display your Svelte application.

Project Structure and Configuration Files

A typical Svelte project structure looks like this:

my-svelte-app/
├── public/
│   ├── index.html
│   └── ...
├── src/
│   ├── App.svelte
│   ├── main.js
│   └── ...
├── package.json
├── rollup.config.js
└── ...
  • public/: Stores static assets such as HTML, CSS, and images.
  • src/: Contains source code, including Svelte components and the entry file.
  • App.svelte: Typically the root component of the application.
  • main.js: The application’s entry file, responsible for bootstrapping the app.
  • package.json: Metadata and dependency information for the project.
  • rollup.config.js: Rollup configuration file for compiling the Svelte application.

Detailed Tutorial and Step-by-Step Code Analysis

To better understand Svelte’s usage, let’s walk through a simple counter application with step-by-step code analysis.

Create a Counter Component: In the src directory, create a file named Counter.svelte with the following code:

<!-- src/Counter.svelte -->
<script>
  export let initialCount = 0;

  let count = initialCount;

  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>Increment</button>
<p>{count}</p>

Use the Counter Component in the Main App: Modify src/App.svelte to import and use the Counter component:

<!-- src/App.svelte -->
<script>
  import Counter from './Counter.svelte';
</script>

<main>
  <h1>Welcome to Svelte!</h1>
  <Counter initialCount={0} />
</main>

Start the Application: Ensure you’ve run npm run dev in the project’s root directory. The browser will automatically refresh to display your application.

In this process, we created a simple counter component with a reactive state variable count and defined an increment function to increase the counter’s value. When the button is clicked, the increment function is called, updating count. Thanks to Svelte’s reactive system, the DOM automatically updates to reflect the new counter value.

Share your love