Trouble implementing new FileUpload feature from GovUK-frontend in Svelte app

I’m stuck trying to use the latest FileUpload component from the GovUK-frontend package in my Svelte 4 project. Here’s what I’ve done so far:

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

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

// HTML goes here

But when I run this, I get an error:

TypeError: HTMLElement is undefined
at /myproject/node_modules/govuk-frontend/components/base.mjs:42:18

Does anyone know how to fix this? I’d rather not use initializeComponents for everything if possible. Any help would be great!

I encountered a similar issue when implementing GovUK-frontend components in a Svelte project. The problem likely stems from the component trying to access the DOM before it’s fully loaded. Instead of using onMount, try wrapping the initialization in a svelte:head block with a script tag. This ensures the code runs after the DOM is ready:

<svelte:head>
  <script>
    import { FileUpload } from 'govuk-frontend/components/upload-file/upload-file.mjs';
    document.addEventListener('DOMContentLoaded', () => {
      new FileUpload(document.querySelector('.govuk-file-upload'));
    });
  </script>
</svelte:head>

This approach initializes only the FileUpload component and avoids using initializeComponents for everything. Remember to include the necessary CSS for the component as well. If you’re still having issues, double-check your build configuration to ensure it’s properly handling ES modules from node_modules.

hey mate, i had the same problem. try using the @sveltejs/kit-adapter-static package. it fixed the HTMLElement undefined error for me. also, make sure ur using the latest version of govuk-frontend. good luck!

hmmm, interesting problem! have u tried using a custom element wrapper for the FileUpload component? Something like this might work:

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

  $: if (fileUploadElement) new FileUpload(fileUploadElement);
</script>

<div bind:this={fileUploadElement}></div>

what do you think? This could bypass the HTMLElement issue. curious to hear if it helps!