2018-12-01

About Lazy loading Ant Design Components overriding custom CSS

problemsolving, programming, react, selfnote

banner

_Photo by Vlad Tchompalov on _Unsplash

🎵 Note to self...

Upgraded Bunpkg React version to v16.6.x (actually v16.7.0-alpha2 to play around with React Hooks ⚓ as well 😀), which enables support for React.lazy.

But lazy loading Ant Design (AntD, hereafter) components broke the custom CSS imported from the root component using CSS import.

🤔 Problem

Custom CSS styles applied on AntD components were not reflected after deploying the site on Netlify even though it was working in development mode.

Custom styles.css was loaded in the root component. 
And below is the custom CSS in index.js was imported.

https://gist.github.com/dance2die/81217485264ccab442ad58026f245433

And "Step" components (for Wizard) were lazily imported as shown below.

https://gist.github.com/dance2die/ea0b127fd9a13a274f70b6a8b9afe952

Rendered Step Components

📊 Analysis

The reason for the different way of import was due to Ant Design's babel-plugin-import automatically optimizing CSS/Component imports.

After monitoring the rendered tree & network tab in Chrome devtool, I saw new CSS chunks were being loaded when accessing new Wizard step components.

What I realized is that AntD components had its own CSS-in-JS, thus lazily loading AntD components loaded CSS after my custom CSS in the head, overriding my style in result.

👷 What I did...

I am still researching but can't figure out how to import CSS in React and keep it as the last style loaded.

So the workaround I adopted was to move styles.css to a static file location (public/) and imported it in the body (as CSS-in-JS chunks were loaded in the head).

https://gist.github.com/dance2die/7a47a15b719a3cf2b2a7979306b04ded