I see that importing the entire lodash library takes up quite a bit of space on disk:
$ du . | grep lodash
1696 ./lodash/fp
5000 ./lodash
In my code I am just doing
require('lodash');
and my package.json just looks like:
"dependencies": {
...
"lodash": "^4.6.1",
...
}
Note that this is for a backend project only, not for web, if that makes a difference.
So my question is - what is the latest way of just importing a slice of lodash (just the functions I need) without importing the whole damn thing?
It looks like here are some answers:
https://gist.github.com/callumlocke/bbfc524eaed6b3556dab
My guess is that I should be using the dot syntax for my backend project:
"dependencies": {
...
"lodash.X": "^4.6.1",
...
}
and then import it like so:
require('lodash.X');
There are two ways to do it:
require('lodash.head')
require('lodash/head')
require('lodash.head')
You install the package with individual function:
npm install --save lodash.head
This adds this to package.json:
"dependencies": {
"lodash.head": "^4.0.1"
}
You use it with:
var head = require('lodash.head');
require('lodash/head')
You install the full lodash
package:
npm install --save lodash
This adds this to package.json:
"dependencies": {
"lodash": "^4.17.4"
}
You use it with:
var head = require('lodash/head');
More complex example:
You can have _
with two functions that you need:
var head = require('lodash.head');
var tail = require('lodash.tail');
var _ = {pick, defaults};
Similar effect, different style:
var _ = {
head: require('lodash.head'),
tail: require('lodash.tail'),
};
If you want only some part of lodash, like e.g. lodash.pick then use:
For more examples of single functions packaged as modules see:
You can also use custom builds, see:
When you use the full package and import only the functions that you need with:
var _ = {
head: require('lodash/head'),
tail: require('lodash/tail'),
};
Then some tools like Webpack may be able to optimize your build to include only the code that you actually use. When you import the entire lodash with:
var _ = require('lodash');
then static analysis cannot be sure which function will be used at runtime so it's harder to optimize well and usually more code is included in the build than is actually needed.
Using ES6 modules, this could be done like this as well:
import isEqual from 'lodash.isequal';
Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With