How to use antd components without the whole library
Recently I got the opportunity to use DatePicker of antd library https://ant.design/components/date-picker/ for a react.js project. It was really cool to use that until I found it was using the whole antd library to import this single antd components. It wasn’t right and there was a solution introduced by the antd team. I just blogged it for anyone who will find it interesting.
How to import antd components
First, you will have to figure out what is the component needed for your project. For me it was material-ui
.
Then install the babel-plugin-import
https://github.com/ant-design/babel-plugin-import using npm. This is responsible to import the library modularly.
npm install babel-plugin-import --save-dev
Then modify the .babelrc configuration file situated in the project folder. If you don’t have one, create it at the root of the project.
"plugins": [ ["import", { "libraryName": "antd", "style": 'css', }, { "libraryName": "material-ui", "libraryDirectory": "components", // default: lib "camel2DashComponentName": false, // default: true } ] ]
Here, you will have to load “style” with css. Even though we have the option of using less, it will bring out import problems due to its comments.
Then use css optimize plugin in the webpack to minimize the css file size.
new OptimizeCssAssetsPlugin(new webpack.LoaderOptionsPlugin({ options: { context: __dirname, postcss: [ require('cssnano')({ discardComments: { removeAll: true }, }), ], }, }),{ cssProcessor: require('cssnano'), }),
That’s it. You can see the file size difference now.