Search code examples
angularangular-clilodashtree-shaking

Reducing Lodash imports / bundle sizes via module


So I'm going through trying to reduce bundle sizes, starting with one of the common culprits -- Lodash, kind of following this article as I go because obviously this is not ideal;

enter image description here

So I go in and start trying to do the basic task of doing the module imports of just what's actually getting used like going from import * as _ from 'lodash' to import each from 'lodash/each'

Except doing that I get as example .../node_modules/@types/lodash/each"' has no default export. Which is confusing, because I see the export in there, I have my @types for it in there showing everything should be fine, but I'm obviously missing some inane detail. Do I have to use lodash-es since my module is es2015? Am I understanding that's why esModuleInterop in the tsconfig set to true will puke at me? Guess I'm just looking for whatever little detail I'm apparently missing.

Angular 6/CLI

Target: es5

Module: es2015


Solution

  • This is the tree-shakeable import:

    import each from 'lodash-es/each';
    

    As the npm package states, it really is just the ES6 module export of the original package:

    The Lodash library exported as ES modules.
    
    Generated using lodash-cli:
    
    $ lodash modularize exports=es -o ./
    See the package source for more details.
    

    Further explanation can be found here: Correct way to import lodash