mcp-svelte-docs

mcp-svelte-docs

4.4

mcp-svelte-docs is hosted online, so all tools can be tested directly either in theInspector tabor in theOnline Client.

If you are the rightful owner of mcp-svelte-docs and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A Model Context Protocol (MCP) server that provides a comprehensive reference guide for Svelte 5, helping LLMs provide accurate guidance when users are working with Svelte.

Evaluation
Total Score: 8/10

Evaluation Summary

  • Strengths:
    1. Accuracy/Correctness: The agent consistently provides accurate and correct information about Svelte 5 features, including $state, event handling, migration patterns, snippets, and common mistakes. It effectively explains new concepts and changes from previous versions, demonstrating a strong understanding of Svelte 5.
    1. Completeness: The agent offers comprehensive answers, covering various aspects of each topic with detailed explanations and examples. This thoroughness ensures that users receive a well-rounded understanding of the subject matter.
    1. Consistency with Claimed Capabilities: The agent delivers on its claimed capabilities, providing detailed documentation, migration guidance, and explanations of new features and common pitfalls in Svelte 5.
    1. Usefulness / Clarity: The answers are well-structured, with clear headings and code examples that enhance readability and comprehension. The inclusion of best practices and strategies adds value for users seeking practical guidance.
  • Weaknesses:
    1. Terminology Inconsistencies: The agent occasionally uses incorrect terminology, such as referring to $state.raw instead of $state.frozen, which could lead to confusion.
    1. Lack of References: The answers do not cite official documentation or authoritative sources, which would enhance credibility and allow readers to explore further.
  • Suggestions for Improvement:
    1. Correct Terminology: Ensure the use of correct and up-to-date terminology to maintain accuracy and prevent confusion.
    1. Include References: Cite official Svelte documentation or other authoritative sources to support the information provided and offer readers avenues for further exploration.
  • Overall, the agent demonstrates a strong understanding of Svelte 5 and provides valuable insights, but minor inconsistencies and the lack of references slightly detract from its overall quality.
  • Test case 1
    Score: 8/10
    Can you provide detailed documentation on the new $state rune in Svelte 5, and explain how it differs from the state management in Svelte 4?

    Documentation on the $state Rune in Svelte 5

    Description

    The $state rune is a new feature in Svelte 5 that allows you to declare reactive state. This makes it easier to manage and update state within your Svelte components.

    Basic Syntax

    You can create reactive state using the $state function:

    // Create reactive state
    let count = $state(0);
    let user = $state({ name: 'Alice', age: 30 });
    
    // Access and update directly
    count++;
    user.name = 'Bob';
    
    Examples
    1. Basic Counter

      <script>
        let count = $state(0);
        
        function increment() {
          count++;
        }
      </script>
      
      <button onclick={increment}>
        Clicked {count} times
      </button>
      
    2. Object State

      <script>
        let user = $state({ name: 'John', age: 30 });
      
        function birthday() {
          user.age++;
        }
      </script>
      
      <div>
        <p>{user.name} is {user.age} years old</p>
        <button onclick={birthday}>Birthday!</button>
      </div>
      
    3. With TypeScript

      <script lang="ts">
        interface User {
          name: string;
          age: number;
        }
      
        let user = $state<User>({ name: 'John', age: 30 });
      
        function birthday(): void {
          user.age++;
        }
      </script>
      
    Raw State

    For values that should only be reactive when reassigned (not when their properties change):

    let numbers = $state.raw([1, 2, 3]);
    
    // This triggers reactivity (reassignment)
    numbers = [...numbers, 4];
    
    // This does NOT trigger reactivity (mutation)
    numbers[0] = 99;
    
    Best Practices
    • Use $state for any value that needs to trigger UI updates when changed.
    • For large arrays or objects that don't need deep reactivity, consider using $state.raw.
    • Avoid exporting $state variables directly from modules; use getter/setter functions instead.
    • When using TypeScript, you can specify the type, e.g., let count = $state<number>(0).

    Differences Between State Management in Svelte 4 and Svelte 5

    Svelte 4 Example

    In Svelte 4, state is simply declared as a variable:

    <script>
      let count = 0;
    
      function increment() {
        count += 1;
      }
    </script>
    
    <button on:click={increment}>
      Clicks: {count}
    </button>
    
    Svelte 5 Example

    In Svelte 5, you use the $state rune for state management:

    <script>
      let count = $state(0);
    
      function increment() {
        count++;
      }
    </script>
    
    <button onclick={increment}>
      Clicks: {count}
    </button>
    

    Summary

    The $state rune in Svelte 5 offers a more structured and reactive approach to managing state compared to the traditional variable declaration in Svelte 4. This change simplifies state updates and enhances reactivity in your components.

  • Test case 2
    Score: 8/10
    Can you explain how event handling in Svelte 5 differs from previous versions, and provide an example of handling both native DOM events and custom component events?

    In Svelte 5, event handling sees significant changes from previous versions. Here’s a breakdown of the key differences and examples of handling both native DOM events and custom component events.

    Differences in Event Handling

    1. Standard HTML Syntax: Svelte 5 adopts standard HTML attributes for event handling instead of the directive syntax used in Svelte 4. This means you use onclick, onsubmit, etc., as you would in regular HTML.

    2. Event Modifiers: Event modifiers from Svelte 4 have been replaced with wrapper functions. For example, instead of using on:click|preventDefault, you would create a function to handle default prevention.

    3. Callbacks for Component Events: In Svelte 5, you handle component events using callback props rather than the event dispatching mechanism used in Svelte 4.

    Examples of Handling Events

    Native DOM Events

    Here are some examples of native DOM event handling:

    <script>
     let count = $state(0);
    
     function handleClick() {
         count++;
     }
    </script>
    
    <button onclick={handleClick}>
     Clicked {count} times
    </button>
    
    <!-- Inline Event Handlers -->
    <button onclick={() => count++}>
     Clicked {count} times
    </button>
    
    <!-- Handling Form Submission -->
    <form onsubmit={(e) => {
        e.preventDefault();
        // Handle form submission
    }}>
     <input type="text" oninput={(e) => name = e.target.value} />
     <button type="submit">Submit</button>
    </form>
    
    Custom Component Events

    For custom component events, you can use callback props. Here’s how you would set that up:

    <!-- Child.svelte -->
    <script>
     let { onMessage } = $props();
    
     function handleClick() {
         onMessage('Hello from Child');
     }
    </script>
    
    <button onclick={handleClick}>
     Send Message
    </button>
    
    <!-- Parent.svelte -->
    <script>
     import Child from './Child.svelte';
    
     let messages = $state([]);
    
     function handleMessage(message) {
         messages = [...messages, message];
     }
    </script>
    
    <Child onMessage={handleMessage} />
    
    <div>
     <h2>Messages:</h2>
     <ul>
     {#each messages as message}
         <li>{message}</li>
     {/each}
     </ul>
    </div>
    

    Best Practices

    • Use standard HTML attributes for event handling.
    • Instead of using event modifiers, create helper functions.
    • Use callback props for component events, prefixed with "on" (e.g., onMessage, onSubmit).
    • Pass data as objects for extensibility.

    These changes simplify event handling, making it more intuitive and consistent with standard HTML practices. If you have any specific scenarios or further questions, feel free to ask!

  • Test case 3
    Score: 8/10
    Can you provide guidance on migrating a Svelte 4 application to Svelte 5, highlighting the key changes and steps involved in the process?

    Migrating a Svelte 4 application to Svelte 5 involves several key changes in syntax and patterns. Here's a summary of the key changes and steps you should consider during the migration process:

    Key Changes and Migration Patterns

    1. Reactive State Management

      • Svelte 4:
        <script>
          let count = 0;
        
          function increment() {
            count += 1;
          }
        </script>
        
        <button on:click={increment}>
          Clicks: {count}
        </button>
        
      • Svelte 5:
        <script>
          let count = $state(0);
        
          function increment() {
            count++;
          }
        </script>
        
        <button onclick={increment}>
          Clicks: {count}
        </button>
        
    2. Reactive Declarations

      • Svelte 4:
        <script>
          let count = 0;
          $: doubled = count * 2;
          $: isEven = count % 2 === 0;
        </script>
        
      • Svelte 5:
        <script>
          let count = $state(0);
          const doubled = $derived(count * 2);
          const isEven = $derived(count % 2 === 0);
        </script>
        
    3. Component Props

      • Svelte 4:
        <script>
          export let name;
          export let age = 21;
        </script>
        
      • Svelte 5:
        <script>
          let { name, age = 21 } = $props();
        </script>
        
    4. Event Handling

      • Svelte 4:
        <button on:click={handleClick}>Click me</button>
        <button on:click|preventDefault={handleSubmit}>Submit</button>
        
      • Svelte 5:
        <button onclick={handleClick}>Click me</button>
        <button onclick={(e) => { e.preventDefault(); handleSubmit(); }}>Submit</button>
        
    5. Lifecycle Methods

      • Svelte 4:
        <script>
          import { onMount, onDestroy } from 'svelte';
        
          onMount(() => {
            const interval = setInterval(() => {
              count += 1;
            }, 1000);
        
            onDestroy(() => {
              clearInterval(interval);
            });
          });
        </script>
        
      • Svelte 5:
        <script>
          let count = $state(0);
        
          $effect(() => {
            const interval = setInterval(() => {
              count++;
            }, 1000);
        
            return () => {
              clearInterval(interval);
            };
          });
        </script>
        
    6. Slots

      • Svelte 4:
        <!-- Card.svelte -->
        <div class="card">
          <div class="header">
            <slot name="header">Default header</slot>
          </div>
          <div class="content">
            <slot>Default content</slot>
          </div>
          <div class="footer">
            <slot name="footer">Default footer</slot>
          </div>
        </div>
        
      • Svelte 5:
        <!-- Card.svelte -->
        <script>
          let { header, default: content, footer } = $props();
        </script>
        
        <div class="card">
          <div class="header">
            {@render header?.() ?? <div>Default header</div>}
          </div>
          <div class="content">
            {@render content?.() ?? <div>Default content</div>}
          </div>
          <div class="footer">
            {@render footer?.() ?? <div>Default footer</div>}
          </div>
        </div>
        
    7. Component Events

      • Svelte 4:
        <!-- Child.svelte -->
        <script>
          import { createEventDispatcher } from 'svelte';
          const dispatch = createEventDispatcher();
        
          function handleClick() {
            dispatch('message', 'Hello from Child');
          }
        </script>
        
        <button on:click={handleClick}>Send Message</button>
        
      • Svelte 5:
        <!-- Child.svelte -->
        <script>
          let { onMessage } = $props();
        
          function handleClick() {
            onMessage?.('Hello from Child');
          }
        </script>
        
        <button onclick={handleClick}>Send Message</button>
        
    8. Store Subscriptions

      • Svelte 4:
        <script>
          import { writable } from 'svelte/store';
        
          const count = writable(0);
        
          function increment() {
            count.update(n => n + 1);
          }
        </script>
        
        <button on:click={increment}>
          Count: {$count}
        </button>
        
      • Svelte 5:
        <script>
          import { state } from 'svelte';
        
          const count = state(0);
        
          function increment() {
            count.value++;
          }
        </script>
        
        <button onclick={increment}>
          Count: {count.value}
        </button>
        

    Best Practices for Migration

    • Migrate one component at a time.
    • Start with leaf components (those with no children).
    • Use Svelte Language Tools to assist with migration.
    • Test thoroughly after each component migration.
    • Consider using the official migration tool when available.

    By following these steps and adapting your code according to the changes outlined above, you should be able to successfully migrate your Svelte 4 application to Svelte 5.

  • Test case 4
    Score: 8/10
    Can you discuss the new snippets feature in Svelte 5, how it replaces slots, and provide some examples of how to use it effectively?

    Snippets in Svelte 5: Overview and Usage

    Snippets are a new feature introduced in Svelte 5 that effectively replace the traditional slots from Svelte 4. They allow developers to define reusable chunks of markup, which can be passed to components, promoting cleaner code and reducing duplication.

    Key Features of Snippets
    • Reusable Markup: Snippets allow you to encapsulate pieces of markup that can be reused across your application.
    • Parameterization: You can pass parameters to snippets, making them flexible and adaptable for different uses.
    • Lexical Scoping: Snippets are only accessible within the scope they are defined, which helps prevent naming collisions.
    • Recursive References: Snippets can reference other snippets or even themselves, enabling recursive structures.

    Basic Syntax

    Here's a brief syntax overview:

    // Child component
    let { header, default: children, item } = $props();
    
    {@render header?.()}
    {@render children?.()}
    {#each items as item}
     {@render item?.(item)}
    {/each}
    
    // Parent component
    <Child>
     {#snippet header()}
     <h1>Title</h1>
     {/snippet}
     <p>Default content</p>
     {#snippet item(data)}
     <div>{data.name}</div>
     {/snippet}
    </Child>
    

    Examples

    Basic Snippet

    You can define a simple snippet like this:

    {#snippet figure(image)}
    <figure>
     <img
     src={image.src}
     alt={image.caption}
     width={image.width}
     height={image.height}
     />
     <figcaption>{image.caption}</figcaption>
    </figure>
    {/snippet}
    
    {@render figure(headerImage)}
    {@render figure(footerImage)}
    
    Passing Snippets to Components

    In this example, snippets are passed to a Table component:

    Table.svelte

    <script>
     let { data, header, row } = $props();
    </script>
    
    <table>
     <thead>
     <tr>{@render header?.()}</tr>
     </thead>
     <tbody>
     {#each data as item}
     <tr>{@render row?.(item)}</tr>
     {/each}
     </tbody>
    </table>
    

    App.svelte

    <script>
     import Table from './Table.svelte';
     const fruits = [
     { name: 'apples', qty: 5, price: 2 },
     { name: 'bananas', qty: 10, price: 1 },
     { name: 'cherries', qty: 20, price: 0.5 }
     ];
    </script>
    
    {#snippet header()}
    <th>fruit</th>
    <th>qty</th>
    <th>price</th>
    <th>total</th>
    {/snippet}
    
    {#snippet row(fruit)}
    <td>{fruit.name}</td>
    <td>{fruit.qty}</td>
    <td>{fruit.price}</td>
    <td>{fruit.qty * fruit.price}</td>
    {/snippet}
    
    <Table data={fruits} {header} {row} />
    
    Recursive Snippets

    You can create recursive structures using snippets as shown below:

    <script>
     let items = $state([
     { name: 'Fruits', children: [
     { name: 'Apple' },
     { name: 'Banana' },
     { name: 'Orange', children: [
     { name: 'Blood Orange' },
     { name: 'Navel Orange' }
     ]}
     ]},
     { name: 'Vegetables', children: [
     { name: 'Carrot' },
     { name: 'Potato' }
     ]}
     ]);
    </script>
    
    {#snippet tree(items)}
     <ul>
     {#each items as item}
     <li>
     {item.name}
     {#if item.children}
     {@render tree(item.children)}
     {/if}
     </li>
     {/each}
     </ul>
    {/snippet}
    
    {@render tree(items)}
    

    Best Practices

    • Use snippets to avoid duplication in your templates.
    • Snippets can be passed as props to components for enhanced modularity.
    • Leverage lexical scoping to maintain clean and manageable code.
    • Utilize parameters for snippets to enhance their flexibility.
    • Snippets can call other snippets or themselves, allowing for complex recursive layouts.

    In summary, snippets in Svelte 5 provide a powerful and flexible way to manage reusable content, making your components more modular and maintainable.

  • Test case 5
    Score: 8/10
    Can you highlight some common mistakes developers make when working with global state patterns in Svelte 5 and provide strategies to avoid these pitfalls?

    Here are some common mistakes developers make when working with global state patterns in Svelte 5, along with strategies to avoid these pitfalls:

    Common Mistakes and Strategies

    1. Exporting State Variables Directly

      • Mistake: Directly exporting a state variable like export { count }; loses reactivity when imported elsewhere.
      • Strategy: Instead, export functions to access and modify the state:
        export function getCount() {
            return count;
        }
        
        export function setCount(value) {
            count = value;
        }
        
    2. Using Object Getters/Setters Incorrectly

      • Mistake: Directly exporting a state variable in an object.
      • Strategy: Use getters and setters to access and modify state:
        export default {
            get count() {
                return count;
            },
            set count(value) {
                count = value;
            },
            increment: () => count++,
        };
        
    3. Mutating State Objects Directly

      • Mistake: Directly modifying nested properties of a state object.
      • Strategy: Create a new object with updated properties instead:
        user = { ...user, name: newName };
        
    4. Forgetting to Use $state.raw for Large Collections

      • Mistake: Using regular $state for large arrays, which can lead to performance issues.
      • Strategy: Use $state.raw for large collections to improve performance:
        let items = $state.raw([...]);
        
    5. Circular Dependencies in Derived Values

      • Mistake: Creating circular dependencies between reactive values, which can lead to infinite loops.
      • Strategy: Ensure reactive flows are unidirectional by clearly defining inputs and outputs.

    Summary

    By being mindful of these common mistakes and implementing the suggested strategies, developers can effectively manage global state in Svelte 5, leading to more robust and maintainable code.