🎭 Svelte’s Secret Control Room: Component Configuration
Imagine your Svelte component is a spaceship. You can fly it around, but what if you want to control the ENTIRE cockpit dashboard, set the ship’s secret settings, or build an emergency shield? That’s where these three special elements come in!
🌟 The Big Picture
Think of your Svelte component like a house:
<svelte:head>= The house’s mailbox & address sign (what the world sees first)<svelte:options>= The house’s blueprint rules (how the house is built)<svelte:boundary>= The house’s fire extinguisher (catches problems before they spread)
Let’s explore each room!
📬 <svelte:head> – Your Page’s Control Tower
What Is It?
<svelte:head> lets you add stuff to the <head> of your HTML document—the invisible part of a webpage that controls things like:
- The title in the browser tab
- The icon (favicon)
- Meta tags for search engines
- Styles and scripts
🏠 Simple Analogy
Think of the <head> as the label on a gift box. People see it BEFORE opening the box. <svelte:head> lets your component write on that label!
📝 Basic Example
<script>
let pageTitle = "Welcome Home!";
</script>
<svelte:head>
<title>{pageTitle}</title>
<meta name="description"
content="My awesome page">
</svelte:head>
<h1>Hello World!</h1>
What happens?
- Browser tab shows: “Welcome Home!”
- Search engines see your description
- Your component controls the page head!
🎯 Dynamic Titles
The magic? You can make it reactive:
<script>
let unreadMessages = 5;
</script>
<svelte:head>
<title>
{unreadMessages > 0
? `(${unreadMessages}) Inbox`
: 'Inbox'}
</title>
</svelte:head>
Now your browser tab shows (5) Inbox – just like real email apps!
⚠️ Important Rules
- Only works in browser – Server-side rendering has special handling
- Last one wins – If multiple components set the title, the last-rendered one wins
- Keep it simple – Only put things that belong in
<head>
graph TD A["Your Component"] --> B["svelte:head"] B --> C[Browser's Head Tag] C --> D["Title Tab"] C --> E["Meta Tags"] C --> F["Favicons"] C --> G["External Styles"]
⚙️ <svelte:options> – The Component’s Secret Settings
What Is It?
<svelte:options> is like a settings panel that tells Svelte HOW to compile your component. It changes the component’s behavior at build time.
🏠 Simple Analogy
Imagine building a LEGO set. The instruction manual tells you HOW to build it. <svelte:options> is YOUR instruction manual for Svelte!
📝 Where It Goes
Always at the TOP of your component file!
<svelte:options immutable={true} />
<script>
// Your code here
</script>
🔧 The Available Options
1. immutable – The “Don’t Touch My Stuff” Rule
<svelte:options immutable={true} />
What it does:
- Tells Svelte: “I promise I won’t secretly change objects”
- Svelte checks if the reference changed, not the contents
- Makes updates FASTER for big lists!
Without immutable:
<script>
let items = [1, 2, 3];
items.push(4); // Svelte watches for this
</script>
With immutable:
<svelte:options immutable />
<script>
let items = [1, 2, 3];
// Must create NEW array to trigger update
items = [...items, 4];
</script>
2. accessors – Adding Getter/Setter Doors
<svelte:options accessors={true} />
<script>
export let count = 0;
</script>
What it does:
- Creates
.countgetter and setter on the component - Useful when using Svelte components from vanilla JS
// From outside (vanilla JS)
const myComponent = new Counter({
target: document.body
});
console.log(myComponent.count); // Works!
myComponent.count = 10; // Also works!
3. customElement – Transform Into a Web Component
<svelte:options
customElement="my-fancy-button"
/>
<button>
<slot>Click me!</slot>
</button>
What it does:
- Turns your Svelte component into a web component
- Use it anywhere: React, Vue, plain HTML!
<!-- In any HTML file -->
<my-fancy-button>
Hello World!
</my-fancy-button>
4. namespace – For SVG and MathML
<svelte:options namespace="svg" />
<circle cx="50" cy="50" r="40"
fill="red" />
What it does:
- Tells Svelte to use SVG or MathML namespace
- Required for components that ARE SVG elements
📊 Quick Reference Table
| Option | Default | Purpose |
|---|---|---|
immutable |
false |
Faster reactivity |
accessors |
false |
External access |
customElement |
null |
Web component |
namespace |
"html" |
SVG/MathML |
🛡️ <svelte:boundary> – Your Error Safety Net
What Is It?
<svelte:boundary> catches errors in child components and prevents your whole app from crashing. It’s like a safety net under a trapeze artist!
🏠 Simple Analogy
Imagine you’re stacking blocks. One wobbly block falls… but instead of everything crashing down, a magic hand catches JUST that block while keeping the rest safe!
📝 Basic Example
<svelte:boundary onerror={handleError}>
<DangerousComponent />
{#snippet failed(error, reset)}
<div class="error-box">
<p>Oops! Something broke.</p>
<p>{error.message}</p>
<button onclick={reset}>
Try Again
</button>
</div>
{/snippet}
</svelte:boundary>
<script>
function handleError(error, reset) {
console.log('Caught:', error);
// Optional: send to error tracking
}
</script>
🔧 How It Works
graph TD A["Parent Component"] --> B["svelte:boundary"] B --> C{Child OK?} C -->|Yes| D["Shows Child"] C -->|Error!| E["Shows failed snippet"] E --> F["Reset Button"] F -->|Click| C
📋 The Two Key Parts
1. onerror Handler
Runs when an error happens:
<script>
function handleError(error, reset) {
// error = the actual error object
// reset = function to retry rendering
console.error('Error caught:', error);
// Send to error tracking service
logToServer(error);
}
</script>
<svelte:boundary onerror={handleError}>
<MyComponent />
</svelte:boundary>
2. failed Snippet
What to show when things break:
<svelte:boundary>
<DataLoader />
{#snippet failed(error, reset)}
<div>
<h3>😢 Something went wrong</h3>
<code>{error.message}</code>
<button onclick={reset}>
🔄 Retry
</button>
</div>
{/snippet}
</svelte:boundary>
💡 Real-World Example
<script>
import UserProfile from './UserProfile.svelte';
import Comments from './Comments.svelte';
</script>
<!-- Each section has its own safety net -->
<svelte:boundary>
<UserProfile />
{#snippet failed(error, reset)}
<p>Profile couldn't load.
<button onclick={reset}>Retry</button>
</p>
{/snippet}
</svelte:boundary>
<svelte:boundary>
<Comments />
{#snippet failed(error, reset)}
<p>Comments unavailable.
<button onclick={reset}>Retry</button>
</p>
{/snippet}
</svelte:boundary>
Now if comments crash, the profile still works!
⚠️ What It Catches
| ✅ Catches | ❌ Doesn’t Catch |
|---|---|
| Render errors | onclick handlers |
| Effect errors | Async errors |
| Lifecycle errors | Errors outside boundary |
🎯 Best Practices
- Wrap risky components – Third-party libraries, data fetchers
- Provide helpful reset – Let users retry
- Log errors – Use
onerrorto track issues - Don’t overuse – One per major section, not every component
🎉 Putting It All Together
Here’s a component using all three special elements:
<svelte:options immutable />
<svelte:head>
<title>My Dashboard</title>
<meta name="robots" content="noindex">
</svelte:head>
<script>
import Widget from './Widget.svelte';
function logError(error) {
console.error('Widget failed:', error);
}
</script>
<h1>Dashboard</h1>
<svelte:boundary onerror={logError}>
<Widget />
{#snippet failed(error, reset)}
<p>Widget error!
<button onclick={reset}>Retry</button>
</p>
{/snippet}
</svelte:boundary>
🧠 Quick Memory Trick
| Element | Think Of | Does |
|---|---|---|
<svelte:head> |
📬 Mailbox | Controls page metadata |
<svelte:options> |
⚙️ Settings | Compiler configuration |
<svelte:boundary> |
🛡️ Shield | Catches errors |
🚀 You’re Ready!
You now understand Svelte’s three component configuration tools:
<svelte:head>– Be the boss of the browser tab<svelte:options>– Fine-tune how your component works<svelte:boundary>– Keep errors from crashing everything
Go forth and build amazing, resilient Svelte apps! 🎭✨
