使用Webpack2时,下面两个import语句有区别吗?

When using Webpack2, is there a difference between the following two import statements?

我正在查看 npm 包的文档并看到以下内容:

Notice that in the above example, we used:

import RaisedButton from 'material-ui/RaisedButton';

instead of

import {RaisedButton} from 'material-ui';

This will make your build process faster and your build output smaller.

使用 Webpack2 时,两种导入在构建速度和包大小方面是否存在差异?

是的。两个导入是不同的,它们确实会影响构建时间和构建输出。

当您使用 import {RaisedButton} from 'material-ui'; 时,您实际上是从主 index.js 文件导入它,该文件还导出其他组件。因此 webpack 最终将在此文件中导出的所有其他组件捆绑在捆绑包中,这增加了捆绑包的大小和捆绑时间。

但是如果您使用 import RaisedButton from 'material-ui/RaisedButton';,那么您是从凸起按钮的 index.js 导入凸起按钮,后者仅导出凸起按钮。因此 webpack 将仅捆绑凸起的按钮,而不会导致更少的捆绑大小和时间。

阅读 React Router 的文档,我发现了以下内容:

If you’re going for a really minimal bundle sizes on the web you can import modules directly. Theoretically a tree-shaking bundler like Webpack makes this unnecessary but we haven’t tested it yet. We welcome you to!

import Router from 'react-router-dom/BrowserRouter'
import Route from 'react-router-dom/Route'

// etc.

所以我认为答案是当使用 Webpack 时,这两个导入在生产环境中应该产生相同的包大小,但是做类似 import {RaisedButton} from 'material-ui'; 的事情可能会导致 webpack 需要更长的时间来打包。