Search code examples
javascriptnpmwebpacklodash

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?


Solution

  • 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