Reputation: 317
I'm a noob so apologie if this question sounds stupid but why do people use _. before lodash function. I've seen people usually use _. like _.cloneDeep() for lodash function but sometimes they seem to use lodash function without anything like here. Is there a reason ?
Upvotes: 0
Views: 1208
Reputation: 4095
It depends on the JavaScript environment you have set up. In some environments, your only option is to use the global underscore (_
) object that has all the functions.
When using a run time or compile time environment that supports ES6 Modules, you can import the functions one at a time like this
import { cloneDeep } from 'lodash';
or this
import cloneDeep from 'lodash/cloneDeep';
There is even an ES6 Module for each function and other package formats as well.
import cloneDeep from 'lodash.clonedeep';
The ES6 Module options can help you make a smaller bundle for your app.
The first two samples - both of which are equivalent - rely on tree shaking to compile a smaller bundle.
In the third example we are only including the functions that we need. However, we will need to npm install --save lodash.clonedeep
for each function that we want to use.
Upvotes: 1
Reputation: 11116
It has to do with how lodash is imported. Most of the time, people say import * as _ from lodash
, so the entire library of lodash is referenced with _
.
However, in the case you provided, they are just importing a single function from lodash by name (which works similarly to object destructuring - it will create a local variable with an identifier equal to that of the property name you are extracting), so there is no need for the _
prefix.
What I prefer to do is something like this:
import { find } from 'lodash';
var _ = { find };
var item = _.find(.....);
And if you're using TypeScript, the Partial
comes in handy here, like so:
var _:Partial<LoDashStatic> = {find};
That way you can get intellisense/type-safety without having to import the entire lodash library. Plus, your syntax doesn't change - it's always prefixed by _.
The reason I like it prefixed is so that I can guarantee the identifiers of imports will never conflict with any local identifiers I have. Also, I can always know at a glance whether something is a lodash method or not, without having to scroll up and look at the imports for that file.
Upvotes: 0
Reputation: 1333
The key there is this line:
import { find } from 'lodash';
In that case they are "extracting" one function from lodash and assigning it to a variable find
.
This is fine if you only need a function or two from lodash. But if you need several, this technique gets a little cumbersome.
Upvotes: 0