3

As you know, there are 2 ways to import MUI component. For example:

import Button from '@mui/material/Button';
// or
import { Button } from '@mui/material';

So my question is: Which way should I use? And any differences between them?

LXT
  • 726
  • 1
  • 7
  • 18
  • Here you go:https://stackoverflow.com/questions/56447187/is-there-a-difference-between-these-two-material-ui-import-methods – gretal Nov 26 '21 at 01:56

2 Answers2

5

I will make it short.

Option 1

import Button from '@mui/material/Button';

You can use this in any scenario. The bundler will only bundle the Button component to your build files instead of the entire MUI library.

Option 2

import { Button } from '@mui/material';

Same as Option 1 IF AND ONLY IF your bundler supports tree-shaking (this is a technical term, google this if you want to know more). If you are using modern frameworks like Create React App, Next.JS, Gatsby, etc. Then they already support tree-shaking out of the box and the choice is purely preference.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Matthew Kwong
  • 2,548
  • 2
  • 11
  • 22
1

Importing individual components like @mui/material/Button reduces the overall bundle size. You don't need to import the whole library, just desired components.

Here is a good resource

Authentic Science
  • 838
  • 1
  • 3
  • 5
  • Yes and no. Your answer is partially correct. Named import will not import the whole library if the bundler support tree shaking. – Matthew Kwong Nov 26 '21 at 08:24
  • True..Assuming developer has configured webpack for tree shaking, and then again building in production mode and/or using webpack 5+. – Authentic Science Nov 26 '21 at 08:41