Lodash one of the most popular libraries which helps to optimize common things and not reinvent the wheel.
When we write code often we import lodash in different ways but is there any difference? is it influences our app?
in order to answer these questions, let's make an experiment.
So first as usual we need a playground, in this case, I will use simple CRA.
npx create-react-app lodash-import-experiment --template typescript && cd lodash-import-experiment && yarn add lodash
before we start to do something lets measure the base size and dependencies structure. analyzing-the-bundle-size, to make the experiment clear I will add some test code which later will be used with Lodash.
Interesting part starts HERE
here is our awesome app code
and its results
First try
import lodash from 'lodash'
Somebody told me once use destructuring import and webpack tree shaking will do the sh*t magic.
Second try
this time let's try to use destructuring import.
import { merge } from "lodash"
as you may see nothing has changed.
Third try
this time tried to use direct import for merge function.
import merge from "lodash/merge"
So as you may see this is the game-changer. import cost is only 12.39 kb vs 71.15 for both destructuring and classic imports. The only bad thing here that you will end-up with import hell.
At this point I started to remember that somebody told me once, "use lodash/fp always it has better tree shaking and there will be no import hell + FP functions written more optimized way so import cost will be definitely less.
So let's check if it's true.
Forth try
import { merge } from 'lodash/fp'
as you may see despite it doesn't help it even brings an additional +8.57kb of weight comparing to destructuring import from lodash. So my pall was definitely wrong.
So I could stop here but I decided to check all cases as in the first part of the experiment with lodash.
Fith try
(to kill curiosity and keep no answered questions)
classic import lodash from "lodash/fp"
also, let's check direct import merge from "lodash/fp/merge"
again as you may see import cost with direct import less comparing to classic and destructuring import.
to sum-up things, I've created a table.
Conclusion
- Always use direct imports (keep only things you need)
- Use fp-funcs only when you really need FP patterns and behavior
Top comments (0)