I’m working on integrating the enhanced file upload component from govuk-frontend version 5.9.0 into my Svelte 4 project. When I try to initialize the component, I keep running into an error.
Here’s my current setup:
import {onMount} from 'svelte';
import { FileUpload } from 'govuk-frontend/dist/govuk/components/file-upload/file-upload.mjs';
import { createAll } from 'govuk-frontend/dist/govuk/init.mjs';
onMount(() => {
createAll(FileUpload);
})
// Template markup goes here
The problem is I’m getting this error when the component tries to load:
ReferenceError: HTMLElement is not defined at file:///myapp/node_modules/govuk-frontend/dist/govuk/component.mjs:57:25
I’m looking for a solution that doesn’t require me to initialize all govuk components if possible. Has anyone encountered this issue before? What’s the best way to handle this HTMLElement reference problem in Svelte?
interesting! are you running this in dev or prod? svelte’s hydration timing can mess with gov.uk components sometimes. try wrapping it in a setTimeout to delay initialization. what exactly does your browser console show when it fails?
You’re experiencing the HTMLElement undefined error because the govuk-frontend library relies on a browser environment. This issue arises in server-side rendering, where DOM APIs like HTMLElement are unavailable. Instead of solely checking for window
, consider using Svelte’s browser check from $app/environment
in SvelteKit, or apply typeof document !== 'undefined'
, as HTMLElement is a part of the DOM. To ensure the DOM is fully loaded, you can move your initialization within a tick() after onMount, ensuring createAll executes only after your template has mounted and all elements are present.
same prob here, it’s all about SSR haha. you gotta check if window exists be4 calling createAll or itll throw an error. just use if (typeof window !== 'undefined')
and it should work! good luck!