Search code examples
javascriptmodulevitesveltedynamic-import

Issue with Dynamic Importing of Svelte Component in JavaScript with Svelte


I'm trying to dynamically import a Svelte component in my project, but I'm encountering a TypeError when including the file extension in the variable that holds the component name.

Here is the working example:

const componentName = "MyComponent";
let importedComponent = (await import(`$myGlobalComponentFolder/myComponent/${componentName}.svelte`)).default;

This code works perfectly fine and successfully imports the component.

However, when I change the code like this (only the file extension is moved):

const componentName = "MyComponent.svelte";
let importedComponent = (await import(`$myGlobalComponentFolder/myComponent/${componentName}`)).default;

I receive the following error:

TypeError: Failed to resolve module specifier '$myGlobalComponentFolder/myComponent/MyComponent.svelte'

Why does the first import work while the second one fails? The logged component path is in both scenarios the same and valid.


Solution

  • If you are using Vite, it should be able to handle this if certain conditions are met (Vite has to be able to identify files that could potentially be targeted by the import path).

    The path alias might be causing issues here, so if you use a relative path (starting with ../ or ./) it might work.

    (Though given that it works with extension this seems more like a bug that a real limitation.)