'What is the difference between the different ways of importing material-ui components?
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?
Solution 1:[1]
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.
Solution 2:[2]
It is because they are exported differently when you export default TextField
you can import TextField
s 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';
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | octobus |
Solution 3 | Tushar Shahi |