2

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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.