Search code examples
angulartypescriptlodashtree-shaking

lodash tree shaking failed with typescript in angular


i have some of big project using typescript.

I've tried several ways to tree shake lodash.

I think it's better to see the output of my work first.

my build command is

build command

ng build --stats-json
webpack-bundle-analyzer {{stats.json path}}

custom_loadsh.ts

export { forEach } from 'lodash/forEach';
export { cloneDeep } from 'lodash/cloneDeep';
...
..
.

app.component.ts

import * as _ from './custom_lodash';
export class AppComponent implements OnInit {
   ...
   ngOnInit() {
       let data = {
          test: 1  
       };
       let data2 = _.cloneDeep(data);
   }
   ...
}

Instead of getting the whole of lodash through custom_lodash, only some of them are imported.

enter image description here

Of course, the example code above is a bit different from the actual project, but the overall configuration is the same.

I wonder why lodash tree shaking fails.

This is the site I referenced. https://medium.com/@martin_hotell/tree-shake-lodash-with-webpack-jest-and-typescript-2734fa13b5cd


Solution

  • I found what was problem.

    the problem is another package in node_modules.

    in my case, ngx-treeview package use lodash.

    this is sample code in ngx-treeview

    import { isNil, isString } from 'lodash';
    

    so, i`ll try below.

    import isNil from 'lodash/isString';
    import isString from 'lodash/isNil';
    

    but.. this solution is temporary.

    i'll try report issue to ngx-treeview github. unfortunately, last edit that package over 1 year.

    so, i just fork that branch.