Lodash Optimization: Import Only Used Functions

💡JavaScript Tip💡 Lodash is the most popular utility library, but most developers make a mistake while using it. Instead of importing the entire library like this: import _ from 'lodash'; Always import only the functions that you're using in your code like this: import isEmpty from 'lodash/isEmpty'; As lodash is a heavy library, using only the required functions will reduce your final application bundle size a lot, as you can see in the image of this post. When using direct functions, only 6.3kb of lodash code is added, whereas using entire library, 71.5kb of code is added into your application. You can install the import cost VSCode extension to see that import size yourself. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

  • No alternative text description for this image

Even better - use lodash-es, the ESM version and do the named import. Easier to read and multiple imports from the same root package.

Like
Reply

Solid tip. To push leaner bundles, consider lodash-es or per-function imports with proper tree-shaking. That way you can stay near the 6.3kb side instead of ballooning to 71.5kb.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories