How to import Ant design on demand to work with components which does destructuring?

Viewed 900

I'm importing antd components on demand in my create-react-app project such as Collapse, Tabs, Select, etc which do some destructure such as:

import { Tabs } from "antd/lib/tabs";
import 'antd/lib/tabs/style/css';
import { Collapse } from "antd/lib/collapse";
import 'antd/lib/collapse/style/css';
import { Select } from "antd/lib/select";
import 'antd/lib/select/style/css';

const { Panel } = Collapse;
const { TabPane } = Tabs;
const { Option } = Select;

I'm getting error TypeError: Cannot destructure property 'Panel' of 'antd_lib_collapse__WEBPACK_IMPORTED_MODULE_3__.Collapse' as it is undefined.
I don't want to use import { Collapse, Select } from "antd"; as it brings a large amount of javascript with it. What am I doing wrong?

2 Answers

One needs to import import Tabs from "antd/lib/tabs"; in such a manner.

Ant design documentation mentions:

antd supports tree shaking of ES modules, so using import { Button } from 'antd'; would drop js code you didn't use.(https://ant.design/docs/react/getting-started#Import-on-Demand).

Additionally, if you are using create-react-app and Ant Design version 4, you might want to load CSS on demand. To get this, follow these steps:

module.exports = {
    babel: {
        plugins: [['import', {
            libraryName: 'antd',
            libraryDirectory: 'es',
            style: 'css',
        }]],
    },
};

  • Finally, Update the existing calls to react-scripts in the scripts section of your package.json file to use the craco CLI:

/* package.json */

"scripts": {
-   "start": "react-scripts start",
+   "start": "craco start",
-   "build": "react-scripts build",
+   "build": "craco build"
-   "test": "react-scripts test",
+   "test": "craco test"
}

Reference: https://programmersought.com/article/95268781523/

Related