I signed the Hope Accord.
4 November 2023

How to fix SvelteKit dynamic imports working in dev but not build

This is mostly for my own future reference, as I just spent a whole day debugging it.

Dynamic imports in SvelteKit must have both the extension and the number of directories hard-coded.

This means that for dynamic nested imports you have to do:

let parts = path.replace(/.w+$/, "").split("/");
let module;

if (parts.length === 1) {
	module = await import(`${parts[0]}.md`);
} else if (parts.length === 2) {
	module = await import(`${parts[0]}/${parts[1]}.md`);
} else if (parts.length === 3) {
	module = await import(`${parts[0]}/${parts[1]}/${parts[2]}.md`);
} else if (parts.length === 4) {
	// ... and so on
}

I find debugging SvelteKit fairly frustrating as it is, but this one was a doozy. No indication of anything wrong in dev (OK there were some warnings that I ignored—Svelte has kind of cried wolf there with a bunch of meaningless CSS stuff filling up the terminal), but cryptic and elusive errors when trying to build or gradually bring a known working example in line with it to home in on the cause.

Anyway, this is one possible way to fix weird dynamic import errors in SvelteKit. Hopefully you found it useful.