About Lazy loading Ant Design Components overriding custom CSS

December 01, 2018
💫 Originally posted here. Broken? Let me know ~

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.

if (process.env.NODE_ENV === "development") {
// Make sure that the custom stylesheet overrides antd css.
import("antd/dist/antd.css").then(() => import("./styles.css"));
} else {
view raw import css.js hosted with ❤ by GitHub

And “*Step” components (for Wizard) were lazily imported as shown below.

import { lazy } from "react";
const SearchPackageStep = lazy(() => import(`./SearchPackageStep`));
const SelectVersionsStep = lazy(() => import(`./SelectVersionsStep`));
const UnpkgLinksStep = lazy(() => import(`./UnpkgLinksStep`));
export { SearchPackageStep, SelectVersionsStep, UnpkgLinksStep };
view raw steps.index.js hosted with ❤ by GitHub
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).

<!DOCTYPE html>
<html lang="en">
    <title>🍔 Bunpkg - B{uild}unpkg{URL}</title>

    <noscript> You need to enable JavaScript to run this app. </noscript>
    <div id="root"></div>
+    <link rel="stylesheet" href="styles.css" />
view raw index.md hosted with ❤ by GitHub