1

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

Chris W.
  • 22,835
  • 3
  • 60
  • 94
  • try lodash-es https://www.npmjs.com/package/lodash-es, I think it does tree-shaking better – mchl18 Sep 24 '18 at 17:50
  • 1
    I still don't understand why some drive-by downvoter wouldn't even give an explanation for their stance.... – Chris W. Sep 25 '18 at 16:32

1 Answers1

1

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

mchl18
  • 2,119
  • 12
  • 20
  • So would you use lodash-es in lieu of lodash or together? Makes sense that es is just lodash as es mods. – Chris W. Sep 24 '18 at 18:00
  • lodash is a dependency of lodash-es. I think the latter just adds proper support for types and tree shaking. Remove lodash and install lodash-es, both should appear in node_modules – mchl18 Sep 24 '18 at 18:12
  • We'll call it good. Almost have it cut in half with lodash-es, now if I could figure out how to mod a chained method like for example `_().last().key;` since it won't let me do like `import * as _ from 'lodash-es'` as a one-for-one import replacement.... – Chris W. Sep 25 '18 at 16:34
  • OH AND JUST TO CLARIFY FOR FUTURE READERS*** `import { each, find } from 'lodash-es';` for example will include the whole library, you need to do separate `import each from 'lodash-es/each';` `import find from 'lodash-es/find';` for example if you want the tree-shaking benefit... – Chris W. Sep 25 '18 at 18:36
  • Is this a drop-in replacement for `lodash` in an existing project, or will it require updating the code? – Hashim Aziz Apr 26 '22 at 16:55
  • 1
    @HashimAziz it's lodash as es6 modules, so the declarations would remain the same but you'd need to update the imports like stated above accordingly. – Chris W. Apr 26 '22 at 17:57