Setup HMR for SvelteKit with Gitpod

How to use Hot Module Reload with SvelteKit and Gitpod

Tom • Svelte & SvelteKit, Tools & Development, Learning •

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;

javascriptLanguageCheck out all coding posts

Now we only have to update the .gitpod.yml-file to define the HMR-port there as well.

#
# .gitpod.yml
# This file is placed at the root of your repo.
#

tasks:
  - init: cd app && npm install
    command: |
      export HMR_HOST=`gp url 3000`
      npm run dev
      
# If you also want to open the preview whenever
# port 3000 gets opened (i.e. you run 'npm run dev'),
# uncomment the next 3 lines.

#ports:
#  - port: 3000
#    onOpen: open-preview

With these small changes, developing your next PWA with SvelteKit works perfectly fine in Gitpod!

Actions

Feedback

Suggested Posts