简体   繁体   中英

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.

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.

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 .

You can read more here

Based on the sources I can find, import x from y; imports the default export from y , calling it x in your file.

So your preferred method is importing the default export 3 times, with 3 different variable names...

Is the preferred method working in production?

Sources:

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

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

I do believe that 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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