Visual editing /Visual Editor /Frameworks /

Use Visual Editor with SvelteKit

Learn how to use Visual Editor with a SvelteKit-based website.

Warning

SvelteKit is an up-and-coming framework gathering enthusiastic support. However, at the time of writing, SvelteKit is still in beta and breaking changes are expected and indeed released from time to time.

When upgrading package versions, code changes may be necessary for either development and/or building for production.

# Configure Visual Editor for a SvelteKit project

SvelteKit is supported through the ssgName: custom option (learn more).

Follow the example repository for a concrete example of integrating Visual Editor with a SvelteKit. Here's an excerpt from Visual Editor configuration file:

// stackbit.config.js
export default {
  stackbitVersion: "~0.6.0",
  cmsName: "contentful",
  nodeVersion: "16",
  ssgName: "custom",
  devCommand: "./node_modules/.bin/vite --port {PORT}",
  experimental: {
    ssg: {
      name: "sveltekit",
      logPatterns: { up: [" ready in "] },
      passthrough: ["/vite-hmr/**"]
    }
  }
};

Note the use of some experimental configuration properties to ensure compatibility with Vite (the development server used by SvelteKit and others):

  1. experimental.ssg.logPatterns.up is set to [' ready in ']. This is part of the log message that appears when the Vite dev server is ready to accept requests.
  2. experimental.ssg.passthrough is set to a dedicated relative path to Vite's HMR Websocket endpoint. The path '/vite-hmr/' is configured accordingly in vite.config.js (see here). With this setting, any code changes will trigger a client refresh through Vite's HMR mechanism, without interference from our container.

# Content reload

In the example repository, content changes are handled by:

  • Capturing the 'stackbitObjectsChanged' window event.
  • Then, invalidating the JSON endpoint providing data to the current page, which will cause the current page to refresh.

This behavior is found at the root __layout.svelte file, which enables it across the website without needing to further modify any other module.

Here are the contents of this file (source):

<script context="module">
  export async function load({ url }) {
    return {
      props: {
        currentUrl: url.pathname,
      },
    };
  }
</script>

<script>
  import { invalidate } from "$app/navigation";
  export let currentUrl;

  function onContentChange(event) {
    invalidate(`${currentUrl}.json`);
    console.log("Content update - invalidating current page");
  }
</script>

<svelte:window
  on:stackbitObjectsChanged|preventDefault={onContentChange}/>

<slot />

# Example

SvelteKit + Contentful Example.

Originally adopted from this demo on GitHub, with added Visual Editor support and modifications for compatibility with the latest version of SvelteKit.