1

From reading the material-ui documentation and online examples, there seem to be different ways of importing the same item:

import TextField from 'material-ui/TextField';
// or
import TextField from '@material-ui/core/TextField';
// or
import { TextField } from '@material-ui/core';

What is the difference between the different way of doing an import?

Greg
  • 7,183
  • 10
  • 56
  • 109

3 Answers3

5

The main difference occurs when bundling. Using the named import:

import { TextField } from '@material-ui/core';

pulls in the entire @material-ui/core module. That means you bundle everything in the module (and all of the dependencies). And there are a lot of components in core.

Importing:

import TextField from '@material-ui/core/TextField';

Only pulls in TextField component (and its dependencies)

I would guess that other paths where TextField can be found (like material-ui/TextField) are for backwards compatibility with previous versions of the library.

Davin Tryon
  • 64,963
  • 15
  • 144
  • 131
1

It is because they are exported differently when you export default TextField you can import TextFields like this,

import TextField from '@material-ui/core/TextField'; Because you can only export default something once in a file.

But if you export const TextField you should import it like this;

import { TextField } from '@material-ui/core';

See this answer for more info

octobus
  • 1,171
  • 1
  • 12
  • 19
1

Adding to @David's answer. For most projects, any of the ways do not matter, provided they have tree shaking enabled. Enabling tree shaking will remove all the unused imports.

This is a subtle difference which highly impacts bundle size. For example, Next.Js projects, where tree shaking has to be added via config explicitly.

Tushar Shahi
  • 10,769
  • 1
  • 9
  • 29