Conditionally Import component from elsewhere, if it does not exist

Viewed 163

I am wondering, if it is possible to import components from a "customer" folder and if it doesn´t exist there, to import it from a "core" folder. Something like this:

import React, {lazy} from 'react'
const MyComponent = lazy('customerFolder/myComponent').then(
    if (!MyComponent) lazy('coreFolder/myComponent')
)

I know, that this code doesn´t work, but I hope you get the point. :) How can I achieve this? Maybe it is a webpack config?

I am using react 16.13 with webpack 4.43.

Thanks in advance.

1 Answers

Maybe its little bit late to answer, but you should catch the exception.

const importComponent= path =>
lazy(() => import(`${path}`).then(comp => comp).catch(err => <p>
 Component not found </p>))

Then you can use it like this:

const Comp = importComponent("./Button");
<Comp onClick={() => alert("Hello World")}>Hello world</Comp>

It will return Component not found text if component is not found :D

Related