Simple Svelte Beginner's Guide: From Project Setup to Component Interaction and Routing Configuration
- 741Words
- 4Minutes
- 29 Jun, 2024
This article will provide a detailed introduction on how to set up a Svelte + TypeScript project using Vite, covering component interaction (parent-child components, data passing and event passing between components), various uses of Store, and routing configuration.
What is Svelte?
Svelte is a modern frontend framework that differs from traditional frameworks (like React and Vue) by compiling components into efficient native JavaScript code at build time rather than interpreting them at runtime. This approach reduces framework overhead, improves performance, and simplifies code structure.
What Can Svelte Do?
Svelte can be used to build modern, responsive frontend applications. It supports component-based development, state management, routing, and other features needed for modern frontend development. Here are some common use cases:
- Single Page Applications (SPA)
- Complex forms and data processing
- Real-time data update dashboards
- Highly interactive user interfaces
Advantages of Svelte
- High Performance: Svelte compiles code into native JavaScript at build time, reducing runtime overhead and improving performance.
- Simple Syntax: Svelte’s syntax is simple and easy to understand, reducing boilerplate code and making development more efficient.
- No Virtual DOM: Svelte directly manipulates the DOM instead of using a virtual DOM, making updates more efficient.
- Lightweight: The generated code is smaller in size, leading to faster load times.
Comparison of Svelte with Vue and React
Compile-time vs. Runtime
- Svelte: Compiles code into efficient native JavaScript at build time.
- React and Vue: Interpret code at runtime and update through a virtual DOM.
Syntax and Development Experience
- Svelte: Simple syntax with less boilerplate code, easy to get started.
- React: Uses JSX syntax, flexible but relatively complex.
- Vue: Uses template syntax, somewhere between Svelte and React, easy to understand.
Performance
- Svelte: Generally performs better due to compile-time optimization.
- React and Vue: Provide good performance through virtual DOM but may not match Svelte in extreme cases.
Initializing the Project
First, create a new Svelte project using Vite and initialize it:
1npm create vite@latest svelte-ts-app -- --template svelte-ts2cd svelte-ts-app3npm install
Project Structure
The project structure is as follows:
1svelte-ts-app/2├── node_modules/3├── public/4│ └── favicon.ico5├── src/6│ ├── assets/7│ ├── components/8│ │ ├── ChildComponent.svelte9│ │ ├── ParentComponent.svelte10│ │ └── SiblingComponent.svelte11│ ├── routes/12│ │ ├── Home.svelte13│ │ └── About.svelte14│ ├── stores/15│ │ └── counter.ts16│ ├── App.svelte17│ ├── main.ts18│ └── index.css19├── .gitignore20├── index.html21├── package.json22├── tsconfig.json23├── vite.config.ts24└── README.md
Configuring TailwindCSS (Optional)
Install TailwindCSS:
1npm install -D tailwindcss postcss autoprefixer2npx tailwindcss init -p
Configure TailwindCSS in tailwind.config.cjs
:
1/** @type {import('tailwindcss').Config} */2module.exports = {3 content: ["./src/**/*.{html,js,svelte,ts}"],4 theme: {5 extend: {},6 },7 plugins: [],8};
Create an index.css
file in the src
directory and add the following content:
1@tailwind base;2@tailwind components;3@tailwind utilities;
Import this CSS file in main.ts
:
1import "./index.css";2import App from "./App.svelte";3
4const app = new App({5 target: document.body,6});7
8export default app;
Creating Components
ChildComponent.svelte
1<script lang="ts">2 import { createEventDispatcher } from "svelte";3
4 export let message: string;5 const dispatch = createEventDispatcher();6
7 function handleClick() {8 dispatch("notify", { text: "Hello from ChildComponent!" });9 }10</script>11
12<div class="p-4 bg-blue-100 rounded">13 <p>{message}</p>14 <button15 on:click={handleClick}16 class="mt-2 bg-blue-500 text-white px-4 py-2 rounded">Notify Parent</button17 >18</div>
ParentComponent.svelte
1<script lang="ts">2 import ChildComponent from "./ChildComponent.svelte";3 import SiblingComponent from "./SiblingComponent.svelte";4
5 let parentMessage = "Message from ParentComponent";6 let childMessage = "";7
8 function handleNotify(event) {9 childMessage = event.detail.text;10 }11</script>12
13<div class="p-4 bg-green-100 rounded">14 <p>{parentMessage}</p>15 <ChildComponent16 message="Message from ParentComponent to ChildComponent"17 on:notify={handleNotify}18 />19 <SiblingComponent message={childMessage} />20</div>
SiblingComponent.svelte
1<script lang="ts">2 export let message: string;3</script>4
5<div class="p-4 bg-yellow-100 rounded">6 <p>{message}</p>7</div>
Using Store
In Svelte, a Store is a mechanism for managing application state, similar to Vuex (Vue) and Redux (React). Svelte provides writable
, readable
, and derived
stores to meet different needs.
stores/counter.ts
1import { writable } from "svelte/store";2
3export const counter = writable(0);
Using Store in Components
1<script lang="ts">2 import { counter } from "../stores/counter";3</script>4
5<div class="p-4 bg-red-100 rounded">6 <button7 on:click={() => ($counter += 1)}8 class="bg-red-500 text-white px-4 py-2 rounded">Increment</button9 >10 <p>Counter: {$counter}</p>11</div>
Using Routing
Installing SvelteKit Routing
1npm install @sveltejs/kit
Configuring Routes
Create route components in the src/routes
directory:
Home.svelte
1<script lang="ts">2 import ParentComponent from "../components/ParentComponent.svelte";3</script>4
5<div class="p-4">6 <h1 class="text-2xl">Home</h1>7 <ParentComponent />8</div>
About.svelte
1<script lang="ts">2 import { counter } from "../stores/counter";3</script>4
5<div class="p-4">6 <h1 class="text-2xl">About</h1>7 <p>Counter: {$counter}</p>8</div>
Configuring Routes
Configure routes in src/App.svelte
:
1<script lang="ts">2 import { Router, Route } from "@sveltejs/kit";3 import Home from "./routes/Home.svelte";4 import About from "./routes/About.svelte";5</script>6
7<Router>8 <Route path="/" component={Home} />9 <Route path="/about" component={About} />10</Router>
Running the Project
Ensure you have installed all dependencies and run the project:
1npm run dev
Summary
- Component Interaction: Demonstrated message passing and event passing between parent and child components, as well as data passing between sibling components.
- Using Store: Showed how to use Svelte’s writable store to manage global state.
- Using Routing: Demonstrated how to configure and use routing with SvelteKit.