AT&T Israel Tech Blog
Published in

AT&T Israel Tech Blog

How to shrink (tree-shake) lodash in bundle file for React Native?

Photo by Samuel Girven on Unsplash

1. Let’s start from the beginning…

2. What is Tree Shaking?

3. Let’s measure out bundle size before reducing it

from the total bundle size, node_modules is 2.95MB !! … and lodash 117KB

4. But before we go forward…let’s make things clear

5. Having said that 😉

☝️ 3 ways to import functions from lodash

  • Import the whole library
import _ from 'lodash';
  • Import specific methods inside of curly brackets
import { map, tail, times, uniq } from 'lodash';
  • Import specific methods one by one
import map from 'lodash/map';
import tail from 'lodash/tail';
import times from 'lodash/times';
import uniq from 'lodash/uniq';
import { map, tail, times, uniq } from 'lodash';
import map from 'lodash/map';
import tail from 'lodash/tail';
import times from 'lodash/times';
import uniq from 'lodash/uniq';
the new bundle size is now: 2.88MB and lodash only 46 KB

6. So until now, it looks that we achieved our goal, but…

import { map, tail, times, uniq } from 'lodash';

The plugins that I tried

7. No choice…making the magic by myself

  • create new file lodashES.ts
  • adding alias into tsconfig.json
snippet of the new configuration to add into tsconfig.json:
  • adding alias into babel.config.json
snippet of alias to add into file babel.config.json
  • and change the syntax in your components files, to use the new lodash alias
run again bundle size analyzer:
  • before mapping lodash : lodash size in bundle file = 117KB
  • after mapping lodash : lodash size in bundle file = 42KB
snippet of .eslintrc.js

Conclusion