Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "import { pick } from 'lodash';" and "import pick from 'lodash/pick';"

What's the difference between

import { pick } from 'lodash';

and

import pick from 'lodash/pick';

(Note that it's 'lodash/pick' in the second one, not just 'lodash'.)

How does do they each affect the bundle size?

Do they import exactly the same parts of lodash?

Are they comparatively fast?

like image 993
Patrickkx Avatar asked Dec 18 '22 20:12

Patrickkx


1 Answers

The lodash module is a roll-up module that imports and reexports from its various individual modules like lodash/pick.

So:

  • import { pick } from 'lodash'; loads the full lodash module and then only imports the one function from it.
  • import pick from 'lodash/pick'; loads only the lodash/pick module and gets its default export (pick).

How does do they each affect the bundle size?

That depends on the degree to which your bundler can do tree-shaking. If pick is the only part of lodash you use, and your bundler can figure that out, it should be about the same. But bundlers vary in terms of the degree and quality of tree-shaking they do.

Do they import exactly the same parts of lodash?

The import the same thing to your module, but in very different ways (see above).

Are they comparatively fast?

In terms of runtime performance, they should be roughly similar, certainly nothing to worry about.

In terms of bundling time, the more work your bundler has to do, the longer it will take; that includes figuring out that although you're importing lodash, you only use pick.

If you really only need pick, the second form should make for less work for the bundler.

But in terms of size, etc., you should probably experiment with your specific setup and your overall code to figure out which is better for you.

like image 82
T.J. Crowder Avatar answered Jan 02 '23 15:01

T.J. Crowder