导入 es6 模块的最佳方法是什么?

What is the best way to import es6 module?

在我看来,我认为这种方式更好,性能更好:

import stuff from 'library/stuff'

所以我没有导入整个库,我只导入了应该更快的模块

但是当我使用 react-router-dom 执行此操作时,我收到警告说我应该改为这样做:

import {Link } from 'react-router-dom'

否则我会收到警告

Warning: Please use `require("react-router-dom").Link` instead of `require("react-router-dom/Link")`. Support for the latter will be removed in the next major release.

这是违反直觉的,所以 导入 es6 模块的第一种方法或第二种方法哪个更好?

import { Link } from 'react-router-dom' 

是正确的做法。我认为性能不会有太大差异。

导入总是加载整个模块,创建所有导出的值,并解析导入的绑定。只使用一个或所有导出的绑定并不重要。导入声明使用什么语法并不重要。

有关更多详细信息,您可以查看此 link: https://alligator.io/js/modules-es6/

这取决于你的环境,

// Import all from utils
import utilities from "utils";


// Import only com1 of the utilities
import { com1 } from "utils";
import com1 from "utils/com1";

在生产版本中

Tree Shaking,Tree shaking 是 JavaScript 上下文中常用的一个术语,用于 dead-code 消除。 在生产构建中,我们可以将 webpack 配置为“摆脱”未明确导入的 ES6 模块的导出,从而使这些生产包更小。

如果您使用的是支持 tree-shaking 的捆绑器,您可以安全地使用命名导入并仍然自动获得优化的捆绑包大小,但是...

在开发环境中

文件可以包含完整的库,这会导致启动时间变慢。那么这个更快:

//Faster
import com1 from "utils/com1";

import { com1 } from "utils";