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
I think the issue is about the name of variable.
Please try to use this:
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.Take a look at Webpack’s Dynamic expressions in import():
When you import like this:
It renders to this, which is not possible:
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 theimport
function itself.A simple solution is to use the following:
Here’s an example sandbox showing this behavior. Here is a discussion on the issue as well.