Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a single lodash methods for smaller builds with browserify/rollup/webpack

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 of the methods: each, map, isArray, etc. The one method I connot get working is lodash/chain.

The current code where I import the whole lodash library goes something like this:

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

What would be the proper way of creating a proper chainable object that does not contain all methods included in the lodash build? The chain method creates a lodash wrapper object and returns it. I could create my own chain 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 call to chain will be able to execute filter and map. Unfortunately, the result from chain().filter will not have the methods I have attached in the original chain. What is the proper way of creating a custom chainable lodash object?

like image 790
jmlopez Avatar asked Mar 13 '16 18:03

jmlopez


1 Answers

There are different solutions to this, although not all of them keep the chain capabilities.

Lodash custom build (keeps chain)

Use https://lodash.com/custom-builds with your custom methods. It will generate a lodash build with the methods you need. The problem I have found in the past with this solution is that the amount of size of the build is quite high even though importing a few methods, as it needs the whole lodash function that wraps your data around it to be able to use the chain.

Import only the functions you need (No chain)

Most of the lodash functions are available as standalone packages in npm (example pick), so you can import them individually. You will not have chain with this solution, though.

Import functions from lodash src (No chain)

Another solution is to import specific functions from your complete lodash module, so any bundler will only take that function with it's dependencies instead of the whole lodash, like:

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

Advice: Don't use chain

Although you asked specifically having the chain, I would like to discourage you from using it, as it is a bad functional programming practice. Check this blog article (as you mentioned in your first comment) for a very thorough explanation on why is better not to use chain, and how to move away from it.

like image 114
Bertofer Avatar answered Oct 04 '22 11:10

Bertofer