Svelte HMR Core Utilities

0.16.0 · active · verified Wed Apr 22

svelte-hmr provides the core logic and utilities for implementing Hot Module Replacement (HMR) in Svelte 3 and 4 applications. It is not an end-user bundler plugin itself, but rather a foundational package leveraged by bundler-specific plugins (e.g., for Rollup, Webpack, Vite) to enable seamless development experiences. The package is currently stable at version `0.16.0` and receives updates as Svelte itself evolves or HMR patterns improve, typically releasing patch and minor versions on an as-needed basis rather than a strict schedule. Key differentiators include its bundler-agnostic design, robust state preservation mechanisms (both component and local variable state), and intelligent CSS injection capabilities, offering a consistent HMR experience across different build tools without needing full page reloads.

Common errors

Warnings

Install

Imports

Quickstart

This Svelte component demonstrates state preservation using `@hmr:keep-all` comments, a feature provided by `svelte-hmr` and enabled via a bundler plugin for a seamless HMR development experience.

<!-- src/App.svelte -->
<script lang="ts">
  // @hmr:keep-all
  // This comment directly influences svelte-hmr's state preservation logic.
  let count: number = 0;
  let textInput: string = 'Edit me!';
  let showDetails: boolean = false;

  function increment() {
    count += 1;
  }

  function toggleDetails() {
    showDetails = !showDetails;
  }
</script>

<style>
  div { padding: 1rem; border: 1px solid #eee; margin-bottom: 1rem; background-color: #f9f9f9; }
  h1 { color: #333; }
  button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-right: 10px;
  }
  input { padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>

<div>
  <h1>HMR Demo Count: {count}</h1>
  <p>Input text: <input type="text" bind:value={textInput} /></p>
  <button on:click={increment}>Increment Count</button>
  <button on:click={toggleDetails}>Toggle Details</button>

  {#if showDetails}
    <p>Details are visible!</p>
    <p>Current input value will persist: "{textInput}"</p>
  {:else}
    <p>Details are hidden.</p>
  {/if}

  <p>
    Modify this Svelte component (e.g., change text, add a new element) and save.
    With a compatible HMR bundler setup (e.g., Vite with <code>@sveltejs/vite-plugin-svelte</code>),
    <code>svelte-hmr</code> will update the component in place, preserving <code>count</code>,
    <code>textInput</code>, and <code>showDetails</code> due to the <code>@hmr:keep-all</code> directive.
  </p>
</div>

view raw JSON →