Don’t Use Lodash Per-Method-Packages

Stefan Matar
The Startup
Published in
2 min readJan 6, 2021
~24kB gzipped according to https://lodash.com/

How do you minimize the size of the lodash dependency?

So you probably started off with some awesome node development. You add all your dependencies and the size of your node_modules folder is increasing slowly into madness.

You add npm i lodash as a dependency as that adds amazing helper functions to your development circle and improves your velocity. All seems fine. But you heard about the possibilty to only add the dependency to a single function of lodash. You find packages like npm i lodash.merge and are astonished of the aprox. 2 million weekly downloads. Woah you should use that, right?

It seems simple: adding the dependency to a single function seems way better and easier to maintain. Also the bundle size should be smaller, considering we only add a single function as a dependency. But there are some pros and cons to this.

Pros could be:

  • You add a dependency to a singular function. If you have breaking changes, reviewing that dependency seems like an easy task.
  • The version number of that dependency is changing less often. Less potential breaking changes.

Cons:

  • Lodash is probably already a peer-dependency of another dependency you may have added.
  • If you use rollup or webpack, you are already tree-shaking your dependencies and only bundling the functions you are using in your codebase.
  • Per-method packages will be deprecated as of v5.

According to lodash you should not use per method packages because of the following reasons:

Although they may seem more lightweight, they will usually increase the size of node_modules and webpack/rollup bundles in a project that transitively depends on multiple per method packages and/or the main lodash package. Whereas many methods in the main lodash package share code, the per method packages internally bundle copies of any code they depend on.

For example, throttle uses debounce internally. In a project using both methods from the main lodash package, throttle will import the same debounce module as any code that imports debounce directly, so only one copy of debounce will wind up in a webpack bundle.

On the other hand, if a project imports throttle from lodash.throttle, the extra copy of the debounce code internally bundled into lodash.throttle will wind up in the webpack bundle, in addition to debounce from the main lodash package or lodash.debounce.

--

--