skip to Main Content

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.

2

Answers


  1. I’m not sure which bundler are you using but bundlers such as Webpack require static paths at compile time to determine which files to include in the bundle. If the file extension is added dynamically using a variable the bundler can’t reliably identify the file. As a result when the path is not fully determined during build time the bundler is unable to resolve it causing the error.

    You can also check the official recommended way of dynamic import here

    Login or Signup to reply.
  2. 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.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search