1

In my project I have a component render the child node according to the current URL, it uses the React.lazy to import the children components. I implement it followed this post answer's code example.

I noticed a strange thing when I implement it, if I import the component using template strings like the following code shows, it works fine.

const Lzy = React.lazy(() => import(`${currentConfig.componentPath}`));

But when I import the components using the variable directly, it always has an error message on the web pages.

const Lzy = React.lazy(() => import(currentConfig.componentPath));


Error Message:

Error: Cannot find module './home/order/OrderForm'
(anonymous function)
src/features lazy groupOptions: {} namespace object:5

The array of currentConfig object

const pathConfig = [{path: "/dashboard/order/new", componentPath: './home/order/OrderForm'}]

Code snippet

    const [CurrentChild, setCurrentChild] = useState(() => () => <div>loading...</div>)
useEffect(() => {
    let currentConfig = pathConfig.find(item => item.path === currentPath)
    if (!!currentConfig) {
        const Lzy = React.lazy(() => import(currentConfig.componentPath));
        //const Lzy = React.lazy(() => import(`${currentConfig.componentPath}`));
        setCurrentChild(Lzy)
    }
}, [currentPath])

Why the first one can work but the second has the can't find the module error, any difference between these two lines code, anyone can help on this?

ZogYi
  • 19
  • 7
  • 1
    See [How do I dynamically import images in React?](https://stackoverflow.com/a/62192731/2873538). You can also write `const Lzy = React.lazy(() => import(currentConfig.componentPath + ''));` which would work. – Ajeet Shah Jan 23 '22 at 13:46

1 Answers1

0

You can't use in that way, You can refer ECMA Doc https://262.ecma-international.org/6.0/#sec-imports

ImportDeclaration :

  • import ImportClause FromClause ;
  • import ModuleSpecifier ;

FromClause :

  • from ModuleSpecifier

ModuleSpecifier :

  • from ModuleSpecifier

A ModuleSpecifier can only be a StringLiteral, not any other kind of expression like an AdditiveExpression.