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

时间:2020-08-05 02:00:02

标签: javascript reactjs react-router es6-modules

在我看来,我认为这种方式更好,更高效:

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模块的更好方法是什么?

2 个答案:

答案 0 :(得分:2)

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

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

导入始终加载整个模块,创建所有导出的值,并解析导入的绑定。只使用一个还是所有导出的绑定都没关系。导入声明使用什么语法都没关系。

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

答案 1 :(得分:1)

这取决于您的环境,

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


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

在生产版本中

这是摇树,摇树是JavaScript上下文中常用的消除死代码的术语。 在生产版本中,我们可以配置webpack来“抑制”未显式导入的ES6模块的导出,从而使这些生产包更小。

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

在开发环境中

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

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

import { com1 } from "utils";