javascript - 逐类导入还是整个模块导入,哪个最好?

标签 javascript reactjs ecmascript-6

我正在开发一个 ReactJS 应用程序,我可以通过两种方式从库中导入类。第一个是使用一个导入子句并在括号中指定我想要的类:

import { makeStyles, CssBaseline, Box } from '@material-ui/core';

第二个是在不同的导入子句中指定每个类:

import makeStyles from '@material-ui/core/makeStyles';
import CssBaseline from '@material-ui/core/CssBaseline';
import Box from '@material-ui/core/Box';

这两种方法有什么区别?哪一个最好?

最佳答案

直接来自文档:

For convenience, Material-UI exposes its full API on the top-level material-ui import. If you're using ES6 modules and a bundler that supports tree-shaking (webpack >= 2.x, parcel with a flag) you can safely use named imports and expect only a minimal set of Material-UI components in your bundle:

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

Be aware that tree-shaking is an optimization that is usually only applied to production bundles. Development bundles will contain the full library which can lead to slower startup times. This is especially noticeable if you import from @material-ui/icons.

您可以使用路径导入来避免引入未使用的模块。

// 🚀 Fast
import Button from '@material-ui/core/Button';

https://material-ui.com/guides/minimizing-bundle-size/

关于javascript - 逐类导入还是整个模块导入,哪个最好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59555299/

相关文章:

javascript - 为什么 redux 调度发生在 Hook 值更新之前?

reactjs - React-native:如何在布局( View )的背景中设置图像

javascript 基于 ES6 中的单个项目对象数组组合对象数组

javascript - 尝试根据特定条件创建趋势公式

Javascript CHAR 插入复制击键

javascript - 在 react 中渲染另一个表的行中的表

javascript - 有效地查找数组中对象的索引

javascript - 如何在 JavaScript 中修复未定义的 "TypeError: Cannot read property ' 映射'?

javascript - Node (ES6) : SyntaxError: Unexpected token {

javascript - React 中类外部的函数或变量