-2

I am using several functions from _ like sortBy . But I do not need complete lodash.

I am using other funtions too from lodash like following

import map from 'lodash/map'

But when I try following

import _ from 'lodash/_'

I get error cannot find module 'lodash/_'

If I simply use following it works

import _ from 'lodash'

But this will carry complete lodash in bundle file which increases size. Can any one please suggest me optimum way to import _ from lodash ?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Krishna
  • 3
  • 1
  • `_` *is* lodash (canonically). I don't understand the question--you're already importing just the functions you need (`import map from...`). I'm not sure what else you're trying to do. – Dave Newton Nov 03 '22 at 16:11
  • 1
    "But this will carry complete lodash in bundle file which increases size. Can any one please suggest me optimum way to import _ from lodash ?" — This doesn't make any sense. Either you want `_` (which is all of lodash) **or** you want to import just the parts you want in order to reduce the bundle size. You can't have it both ways! – Quentin Nov 03 '22 at 16:13
  • Does this answer your question? [Why webpack doesn't tree-shake the lodash when using "import \* as \_"?](https://stackoverflow.com/questions/58741044/why-webpack-doesnt-tree-shake-the-lodash-when-using-import-as) – Andrew Allen Nov 03 '22 at 16:23
  • Thank you @DaveNewton I was not aware of `_` is lodash . Issue solved – Krishna Nov 03 '22 at 17:21
  • (@Krishna Just out of curiosity, what did you think it was? On the [lodash homepage](https://lodash.com/) they differentiate between loading the full build and individual functions.) – Dave Newton Nov 03 '22 at 18:02

1 Answers1

0

You can install Lodash via NPM and then import only single functions. This works as follows:

import { merge, isEqual } from 'lodash';

// use them like regular functions
merge({ a: 1 }, { b: 2 });
  • This way of importing methods results in a higher bundle side. Instead, do this, `import merge from 'lodash/merge'; import isEqual from 'lodash/isEqual'; ` – Antajo Paulson May 25 '23 at 20:59
  • 1
    Could you elaborate why this would occur? I figured since the code is compressed and tree shaked via a bundler like Rollup, that the bundle size would be the same. – Felix Ranesberger Jun 02 '23 at 07:47
  • Webpack can perform tree shaking automatically on ES6 modules. But it looks like lodash is built to use Common-JS modules. I think (lodash-es)[https://www.npmjs.com/package/lodash-es] uses ES6 module. So if you're using lodash-es you can have the intended result with "tree-shaking" – Antajo Paulson Jun 05 '23 at 16:33