【问题标题】:What is the best way to import es6 module?导入 es6 模块的最佳方法是什么?
【发布时间】:2020-08-05 02:00:02
【问题描述】:

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

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

【问题讨论】:

  • 不管有什么警告,react-router-dom/Link 也有用吗?
  • @SILENT 是的,我认为它有效
  • 嗯,不知道。它确实会有所不同,但如果您使用的是 webpack,则 tree-shaking 应该可以消除差异。
  • 什么是摇树?
  • 简而言之,由于 tree-shaking,所有来自 react-router-dom 的“未使用”导出都不会捆绑在生产构建中。您可以通过webpack.js.org/guides/tree-shaking 了解更多信息

标签: javascript reactjs react-router es6-modules


【解决方案1】:
import { Link } from 'react-router-dom' 

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

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

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

【讨论】:

    【解决方案2】:

    这取决于你的环境,

    // 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 上下文中常用的一个术语,用于消除死代码。 在生产版本中,我们可以将 webpack 配置为“摆脱”未明确导入的 ES6 模块的导出,从而使这些生产包更小。

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

    在开发环境中

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

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

    import { com1 } from "utils";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 2015-11-21
      • 1970-01-01
      • 2011-09-16
      • 2020-06-03
      相关资源
      最近更新 更多