简体   繁体   English

从'lib'导入{fn1}与从'lib'导入fn1

[英]import {fn1} from 'lib' vs import fn1 from 'lib'

I am importing a few functions from lodash and my coworker tells me that it's better to import each function separately than to import them as a group. 我从lodash导入了一些函数,我的同事告诉我,最好分别导入每个函数,而不是将它们作为一个组导入。

Current method: 当前方法:

import {fn1, fn2, fn3} from 'lodash';

Preferred method: 首选方法:

import fn1 from 'lodash/fn1';
import fn2 from 'lodash/fn2';
import fn3 from 'lodash/fn3';

Her reasoning is that latter imports less code, as it won't import the entire lodash library. 她的理由是后者会导入较少的代码,因为它不会导入整个lodash库。

Is that the case? 是这样吗

What you want (and what is preferred) is called tree shaking : 您想要的(以及首选)被称为摇树

Tree-shaking is the process of removing unused code during the bundle process. 摇树是在捆绑过程中删除未使用的代码的过程。

The correct way to do this and utilize the tree shaking is: 执行此操作并利用树抖动的正确方法是:

import foo from 'lodash/foo' // <-- only import `foo`

This will not tree-shake: 不会摇晃:

import { foo } from 'lodash'

nor will, obviously this: 显然不会:

import _ from 'lodash' 

Support for this syntax was implemented in Lodash v4 . Lodash v4中实现了对此语法的支持。

You can read more here 你可以在这里阅读更多

Based on the sources I can find, import x from y; 根据我可以找到的来源, import x from y; imports the default export from y , calling it x in your file. y导入默认导出,在文件中将其称为x

So your preferred method is importing the default export 3 times, with 3 different variable names... 因此,您的首选方法是使用3个不同的变量名称导入默认导出3次。

Is the preferred method working in production? 首选方法在生产中可行吗?

Sources: 资料来源:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

https://medium.com/javascript-in-plain-english/javascript-modules-for-beginners-56939088f7d9 https://medium.com/javascript-in-plain-english/javascript-modules-for-beginners-56939088f7d9

I do believe that import {fn1, fn2, fn3} from 'lodash'; 我确实相信是import {fn1, fn2, fn3} from 'lodash'; is the correct way to import different exports of module, however, I think it could be better to use this way 是导入模块的不同导出的正确方法,但是,我认为使用这种方法可能会更好

    import {
      fn1, 
      fn2, 
      fn3
    } from 'lodash';

Since it is easier to remove any of them if it no longer requires 因为如果不再需要它们,则更容易删除它们中的任何一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM