snso
snso

Reputation: 329

What is the right import for lodash constructor?

I am working on some Angular projects and use lodash as helper. I read a lot of articles about how to import lodash the right way to make the bundle size smaller. But I got a problem with my current implementation because I use lodash chaining method.

return _(items)
  .groupBy(x => x.vote.code)
  .map(items => items)
  .value();
import * as _ from 'lodash';

I read import * is not good. My problem is how can I import _(items) so that my import looks like below?

import groupBy from 'lodash/groupBy';

Upvotes: 3

Views: 784

Answers (2)

VLAZ
VLAZ

Reputation: 29116

If you want to reduce your bundle size, you want to avoid importing the whole of Lodash. Instead, you can just import the functions you want - groupBy and map.

However, in this case you are also using chaining, which does require all of Lodash. You can re-write your code using flow and use the functional programming-friendly bundle of Lodash to replace the chaining:

import {flow, groupBy, map} from 'lodash/fp';

/* ... */

const chainReplacement = flow(groupBy(x => x.vote.code), map(items => items));
return chainReplacement(items)

Here is a quick illustration that the two produce equivalent results:

const {flow, groupBy, map} = _;

//sample data
const items = [
  { vote: { code: "1" }, name: "Alice"},
  { vote: { code: "2" }, name: "Bob"},
  { vote: { code: "1" }, name: "Carol"},
  { vote: { code: "2" }, name: "Dave"},
  { vote: { code: "1" }, name: "Edel"}
];

//using literally the same functions
const groupByCallback = x => x.vote.code;
const mapCallback = items => items.length;

const chain = _(items)
  .groupBy(groupByCallback)
  .map(mapCallback);

const chainReplacement = flow(
  groupBy(groupByCallback), 
  map(mapCallback)
);

console.log("chain", chain.value())
console.log("chainReplacement", chainReplacement(items))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-fp/0.10.4/lodash-fp.min.js"></script>

I made some data that matched your usage of groupBy but then had to modify the map callback because it didn't make sense. I assume because it was for illustrative purposes. So I swapped it for items => items.length to get the count of each group. It's not very meaningful but it's also for illustrative purpose only.

Upvotes: 3

Jack Bashford
Jack Bashford

Reputation: 44145

If you only want to import one function or group of functions:

import { groupBy } from "lodash";

Upvotes: 0

Related Questions