Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between these two Material-UI import methods?

When using material-ui, I've been following the docs and importing using the method below

import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';

however, I recently came across some code where the above would have instead been imported as

import { Dialog, DialogTitle, DialogContent } from '@material-ui/core';

The second method of importing obviously looks much cleaner, so is there any reason the docs and most code you'll find online all import it the first way?

like image 307
Michael Avatar asked Apr 15 '26 11:04

Michael


2 Answers

material-ui is a library with a lot of components. In the first case you have imported just those components that you need in your project:

import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';

In the second case

import { Dialog, DialogTitle, DialogContent } from '@material-ui/core';

you have imported all components, even those you don't need. This could greatly increase the size of a bundle with unused dead-code in case if your module bundler has no tree shaking functionality.

I recommend you to use import {...} from '@material-ui/core' only if you know that your module bundler has tree shaking and you switched on this functionality. Or you could use this case if you using almost all components from @material-ui/core.

You could react about tree shaking in webpack here

like image 143
Andrii Golubenko Avatar answered Apr 18 '26 00:04

Andrii Golubenko


In this way you importing the whole package:

import { Dialog, DialogTitle, DialogContent } from '@material-ui/core';

However, you can import individual components on demand:

import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';

If you using VSCode, you can check the import size using Import Cost extension.

It's important to mention that there are plugins for importing components on demand like babel-plugin-import, in this way you import individual components under the scene.

like image 40
Dennis Vash Avatar answered Apr 18 '26 00:04

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!