A Svelte component file (.svelte) holds all parts needed to create a UI piece in one place. It makes building web apps simple and organized.
0
0
Component file (.svelte) anatomy
Introduction
When you want to build a reusable button with its own style and behavior.
When creating a small part of a webpage like a header or footer.
When you want to keep HTML, CSS, and JavaScript together for easy editing.
When building interactive UI parts that update automatically.
When you want to share UI pieces across different pages or projects.
Syntax
Svelte
<script> // JavaScript code here </script> <style> /* CSS styles here */ </style> <!-- HTML markup here -->
The <script> tag holds JavaScript for logic and data.
The <style> tag holds CSS scoped to this component only.
Examples
A simple button that counts clicks using JavaScript inside
<script>.Svelte
<script> let count = 0; </script> <button on:click={() => count++}> Clicked {count} times </button>
CSS styles inside
<style> apply only to this component's button.Svelte
<style>
button {
background-color: lightblue;
padding: 0.5rem 1rem;
border: none;
border-radius: 0.25rem;
}
</style>Using
export let to accept a value from outside the component.Svelte
<script> export let name = 'Friend'; </script> <h1>Hello {name}!</h1>
Sample Program
This component greets a user by name and has a button that counts clicks. It shows how HTML, CSS, and JavaScript live together in one .svelte file.
Svelte
<script> export let name = 'Visitor'; let count = 0; </script> <style> h1 { color: teal; font-family: Arial, sans-serif; } button { background-color: coral; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.3rem; cursor: pointer; } </style> <h1>Welcome, {name}!</h1> <button on:click={() => count++} aria-label="Click to increase count"> Clicked {count} times </button>
OutputSuccess
Important Notes
Each .svelte file is a self-contained component with its own logic, style, and markup.
Styles inside <style> are scoped, so they won't affect other parts of your app.
Use export let to pass data into components from outside.
Summary
A .svelte file combines JavaScript, CSS, and HTML in one place.
This makes components easy to build, read, and reuse.
Scoped styles keep your design neat and avoid conflicts.