Method 1: We can directly use the file in the browser. Go to the official documentation and copy the lodash. min. js file CDN link and paste this link inside the head section.
To start using Lodash in React, you need to:Install Lodash by running npm install lodash. Import Lodash to your project by writing import _ from lodash.
Using your command line, install Lodash in your project folder. And then import it at the top of your JavaScript file in which you would like to use it. You're ready to use Lodash! You can now access all of Lodash's functions inside the “_” object.
import has from 'lodash/has';
is better because lodash holds all it's functions in a single file, so rather than import the whole 'lodash' library at 100k, it's better to just import lodash's has
function which is maybe 2k.
If you are using webpack 4
, the following code is tree shakable.
import { has } from 'lodash-es';
The points to note;
CommonJS modules are not tree shakable so you should definitely use lodash-es
, which is the Lodash library exported as ES Modules, rather than lodash
(CommonJS).
lodash-es
's package.json contains "sideEffects": false
, which notifies webpack 4 that all the files inside the package are side effect free (see https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free).
This information is crucial for tree shaking since module bundlers do not tree shake files which possibly contain side effects even if their exported members are not used in anywhere.
Edit
As of version 1.9.0, Parcel also supports "sideEffects": false
, threrefore import { has } from 'lodash-es';
is also tree shakable with Parcel.
It also supports tree shaking CommonJS modules, though it is likely tree shaking of ES Modules is more efficient than CommonJS according to my experiment.
Import specific methods inside of curly brackets
import { map, tail, times, uniq } from 'lodash';
Pros:
- Only one import line(for a decent amount of functions)
- More readable usage: map() instead of _.map() later in the javascript code.
Cons:
- Every time we want to use a new function or stop using another - it needs to be maintained and managed
Copied from:The Correct Way to Import Lodash Libraries - A Benchmark article written by Alexander Chertkov.
You can import them as
import {concat, filter, orderBy} from 'lodash';
or as
import concat from 'lodash/concat';
import orderBy from 'lodash/orderBy';
import filter from 'lodash/filter';
the second one is much optimized than the first because it only loads the needed modules
then use like this
pendingArray: concat(
orderBy(
filter(payload, obj => obj.flag),
['flag'],
['desc'],
),
filter(payload, obj => !obj.flag),
If you are using babel, you should check out babel-plugin-lodash, it will cherry-pick the parts of lodash you are using for you, less hassle and a smaller bundle.
It has a few limitations:
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