Implementing the new FileUpload feature from GovUK-frontend in Svelte

Hey everyone,

I’m working on a Svelte 4 project and I want to use the latest FileUpload component from the GovUK-frontend package (version 5.9.0). I’ve tried to set it up, but I’m running into some issues.

Here’s what I’ve done so far:

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

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

// HTML goes here

When I run this, I get an error saying:

TypeError: Document is undefined at /myproject/node_modules/govuk-frontend/dist/govuk/element.mjs:42:18

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

hey there! i’m curious, have you tried using svelte:head to include the govuk-frontend styles? that might help with the rendering. also, what about using a custom action instead of onmount? like this:

<script>
  import { FileUpload } from 'govuk-frontend/dist/govuk/components/file-upload/file-upload.js';

  function initFileUpload(node) {
    new FileUpload(node);
    return { destroy: () => {} };
  }
</script>

<div use:initFileUpload class="govuk-file-upload"></div>

what do you think? would that work for your setup?

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. To resolve this, you might want to try wrapping the initialization code in a tick() function.

Here’s a potential solution:

import { onMount, tick } from 'svelte';
import { FileUpload } from 'govuk-frontend/dist/govuk/components/file-upload/file-upload.mjs';

onMount(async () => {
    await tick();
    new FileUpload(document.querySelector('.govuk-file-upload'));
});

This approach ensures the DOM is ready before initializing the component. Also, make sure you’ve included the necessary CSS for the FileUpload component. If you’re still facing issues, consider checking if there are any Svelte-specific wrappers for GovUK-frontend components that might simplify the integration process.

yo zack, ran into this too. try using the browser module instead of the mjs one. like this:

import { FileUpload } from 'govuk-frontend/dist/govuk/components/file-upload/file-upload.js';

that fixed it for me. let me kno if it works!