Does importing one function require loading the whole library?

Viewed 129

I have seen posts on StackOverflow where people are saying "Those features can be implemented easily without using lodash".

Sure, it takes time to install libraries but when you

import { throttle } from 'lodash'

Does this import slow down the page because lodash is a big library? Or is it OK because I am only importing throttle?

Don't focus on lodash specifically but think of it as some huge library and I am trying to use only one function from it.

p.s. I am using React (created with CRA) so bundler is webpack by default

1 Answers

If you're building this code with something like webpack, rollup or some other tool that converts modules into a single script file, what will be pushed to the client will depend heavily on what tool you're using. A simple build tool would simply output the whole of lodash onto the output script; whereas something like rollup (and maybe webpack too?) do some complicated things to trim libraries down to just the parts you're using. Of course, if the throttle function depends on other parts of lodash, those other parts will also have to be included.

If this is module code running on the client (if it were import {...} from "./lodash.js" or if it used the still-experimental import maps), things are more complicated than that. The browser will of course have to read the entire ./lodash.js file, otherwise it won't be able to find the function. But it's my understanding that the contents of the functions themselves won't be even fully processed until they're used.

Related