Download one lodash method for small collections using the / rollup / webpack browser

From https://lodash.com/ :

// Load a single method for smaller builds with browserify/rollup/webpack. var chunk = require('lodash/chunk'); var extend = require('lodash/fp/extend'); 

This works well with most methods: each , map , isArray , etc. One method I got is working lodash/chain .

The current code into which I import the entire lodash library looks something like this:

 _.chain(items) .filter(...) .groupBy(...) .map(...) .concat(...) .value(); 

What would be the right way to create the right object with goals that does not contain all the methods included in the lodash assembly? The chain method creates a lodash shell object and returns it. I could create my own chaining method like this

 var lodash = require('lodash/wrapperLodash'); var filter = require('lodash/filter'); var map = require('lodash/map'); function chain(value) { var result = lodash(value); result.__chain__ = true; result.filter = filter result.map = map; return result; } module.exports = chain; 

Now the chain call will be able to perform filter and map . Unfortunately, the result from chain().filter will not have the methods that I attached in the original chain. What is the correct way to create a custom lodash object for chaining?

+5
source share
1 answer

There are different solutions for this, although not all of them retain the capabilities of the chain.

Custom Lodash assembly (keeps the chain)

Use https://lodash.com/custom-builds with your custom methods. It will create the lodash assembly using the methods you need. The problem that I encountered in the past with this solution is that the assembly size size is quite high, although when importing several methods, as this requires the entire lodash function that wraps your data around it in order to be able to use the chain.

Import only the functions you need (no chain)

Most lodash features are available as standalone packages in npm ( example selection ), so you can import them separately. However, you will not have a chain with this solution.

Import functions from lodash src (no chain)

Another solution is to import certain functions from your full lodash module, so any connected one will use this function only with these dependencies, and not with the whole lodash, for example:

 var pick = require('lodash/pick'); 

Tip. Do not use chaining

Despite the fact that you asked a question about a specific chain, I would like to dissuade you from using it, since this is a bad practice of functional programming. Check out this blog article (as you mentioned in your first comment) for a very detailed explanation of why it’s best not to use the chain and how to move away from it.

+1
source

Source: https://habr.com/ru/post/1244968/


All Articles