skip to Main Content

I am build an Configurable Tab in React.js. I pass the all tab into to the Tab component and build the tabs and the tab content. I use the import(${path}) to load the component in the tabs dynamically.

useEffect(() => {
    const path = '../Clock.tsx';
    const loadComponent = async (index) => {
      const componentModule = await import(`${path}`);
      setComponent(() => componentModule.default);
    };
    loadComponent(activeTab);

  }, [activeTab,props.tabs]);

the above code gives me error ‘Error: Cannot find module ‘../Clock.tsx’.
If i change the import code to import('../Clock.tsx'); it works.

What am i doing wrong.
Git Code for reference: https://github.com/HimanshuK18/react-app/commit/90527c836ab1298b09550bcbb3d8aa41a5c1e843

Similar code in this file works.
https://github.com/HimanshuK18/react-app/blob/8de716a407d0d2605a4f455e039519099fbdcf35/src/projects/Tab/DynamicImport.jsx

2

Answers


  1. I think the issue is about the name of variable.

    Please try to use this:

    const componentModule = await import(path);
    

    If you pass path as an variable into template string, it will consider the variable content includes the single quotes, which makes the error happened.

    Login or Signup to reply.
  2. Take a look at Webpack’s Dynamic expressions in import():

    It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

    The import() must contain at least some information about where the module is located.

    When you import like this:

    await import(`${path}`);
    

    It renders to this, which is not possible:

    await import(path);
    

    You run into this problem because your dynamic import contains no direct information about where the Clock component path is. You have the path information inside the path variable (../), however, that should be moved to within the import function itself.

    A simple solution is to use the following:

    const path = 'Clock';
    ...
    const componentModule = await import(`../${path}`);
    

    Here’s an example sandbox showing this behavior. Here is a discussion on the issue as well.

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