
React v16.6.0 introducedReact.lazy
that allows to code split without any external libraries.
https://reactjs.org/blog/2018/10/23/react-v-16-6.html
The React.lazy function lets you render a dynamic import as a regular component.
Before:
importOtherComponentfrom'./OtherComponent';functionMyComponent(){return(<div><OtherComponent/></div>);}
After:
constOtherComponent=React.lazy(()=>import('./OtherComponent'));functionMyComponent(){return(<div><OtherComponent/></div>);}
Althought bellow there is a message
React.lazy
takes a function that must call a dynamicimport()
. This must return aPromise
which resolves to a module with adefault
export containing a React component.
Which means that yourOtherComponent
should be exported this way
exportdefaultfunctionOtherComponent(){return(<div>OtherComponent</div>);}
But what if you have it exported not as default?
exportfunctionOtherComponent(){return(<div>OtherComponent</div>);}
In this case you have to change a bit theimport()
code when importing this component
constOtherComponent=React.lazy(()=>import('./OtherComponent').then(module=>({default:module.OtherComponent})));
What are we doing here, is just chaining thePromise
returned byimport()
and adding that default export.
Please keep in mind that component imported withReact.lazy
should be rendered inside aReact.Suspense
https://reactjs.org/docs/code-splitting.html#suspense
Cover Photo byScott Kelley onUnsplash
Top comments(5)

Thank you!

Yes. Dynamic import cannot be analyzed at build time.
You will have to follow React Docs and reexport only wanted component to have dynamic import with tree shaking
reactjs.org/docs/code-splitting.ht...
For further actions, you may consider blocking this person and/orreporting abuse