Svelte 4 compatibility issue with new GovUK-frontend FileUpload component

Hey folks, I’m having trouble with the latest GovUK-frontend package in my Svelte 4 project. I’m trying to use the new FileUpload component, but I’m running into a weird error.

Here’s what I’ve got in my code:

import {onMount} from 'svelte';
import { FileUpload } from 'govuk-frontend/components/file-upload.mjs';
import { initComponent } from 'govuk-frontend/setup.mjs';

onMount(() => {
    initComponent(FileUpload);
})

// HTML stuff goes here

When I run this, I get an error saying:

TypeError: Document is undefined at path/to/govuk-frontend/component.mjs:42:18

Any ideas on how to fix this? I’d rather not use the full initialization if I can help it. Thanks in advance for any help!

I encountered a similar issue when upgrading to Svelte 4 with GovUK-frontend components. The problem likely stems from the component trying to access the document object during server-side rendering. To resolve this, consider using the browser directive in your script tag:

<script context="module">
  import { browser } from '$app/environment';
</script>

<script>
  import { onMount } from 'svelte';
  import { FileUpload } from 'govuk-frontend/components/file-upload.mjs';

  onMount(() => {
    if (browser) {
      const { initComponent } = import('govuk-frontend/setup.mjs');
      initComponent(FileUpload);
    }
  });
</script>

This approach ensures the component initialization only occurs on the client side, avoiding the ‘Document is undefined’ error during server-side rendering. It is a robust solution for Svelte 4 projects using SSR.

hmm, intresting problem! have u tried using the browser module instead? like this:

import { FileUpload } from ‘govuk-frontend/components/file-upload/FileUpload.js’;

it might solve the doc undefined issue. also, curios - are u using any specific svelte adapters? they can sometimes affect how components behave in SSR

hey swimingfish, ran into similar issue. try wrapping ur initComponent call in a check for window.document:

if (typeof window !== ‘undefined’ && window.document) {
initComponent(FileUpload);
}

worked 4 me. svelte4 SSR can b tricky w/ components that need DOM. lmk if it helps!