Setup HMR for SvelteKit with Gitpod

How to use Hot Module Reload with SvelteKit and Gitpod

SvelteKit and Gitpod

If you want to make full use of SvelteKit and its “Hot Module Reloading” in Gitpod, a small change to your configuration is required to make it work. If not, you’ll most likely experience a reload happening every few seconds instead of only when you save changes.

Using Vite’s HMR in Gitpod

The following code snippet shows a simple configuration, where we change the part that’s relevant for Vite to work.

We basically tell Vite how our URL actually looks and what protocol to use, as we need to make sure to use WebSocket and not HTTPS in the context of Gitpod.

import adapter from "@sveltejs/adapter-auto";
import preprocess from "svelte-preprocess";

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: preprocess(),
  kit: {
    adapter: adapter(),
    vite: {
      server: {
        // Configure Vite for HMR with Gitpod.
        hmr: process.env.GITPOD_WORKSPACE_URL
          ? {
              // Due to port fowarding, we have to replace
              // 'https' with the forwarded port, as this
              // is the URI created by Gitpod.
              host: process.env.GITPOD_WORKSPACE_URL.replace("https://", "3000-"),
              protocol: "wss",
              clientPort: 443
          : true

export default config;

With this small change, developing your next PWA with SvelteKit works perfectly fine in Gitpod!