The right way to import lodash

I had feedback on the pull request below, just wondering which way is the right way to import lodash?

You are better off importing from 'lodash / has' .. For an earlier version of lodash (v3), which is pretty heavy in itself, we should only import the specidic module / function instead of importing the entire lodash library. Not sure about the newer version (v4).

import has from 'lodash/has'; 

against

 import { has } from 'lodash'; 

thank

+129
javascript lodash babeljs
Feb 07 '16 at 6:32
source share
5 answers

import has from 'lodash/has'; better because lodash contains all the functions in a single file, so instead of importing the entire lodash library into 100k, it’s better to just import the lodash has function, which can be 2k.

+176
Feb 07 '16 at 7:48
source share

If you are using webpack 4, the following code will be a compressible tree.

 import { has } from 'lodash-es'; 

Remarks;

  1. CommonJS modules do not tremble from the tree, so you definitely need to use lodash-es , which is the Lodash library exported as ES modules, not lodash (CommonJS).

  2. lodash-es package.json contains "sideEffects": false , which notifies web package 4 that all files inside the package are free from side effects (see https://webpack.js.org/guides/tree-shaking/ # mark-the -file-as-side-effect-free ).

  3. This information is critical for shaking trees, since modular bundles do not create tree shaking files that may contain side effects, even if their exported elements are not used anywhere else.

edit

Starting with version 1.9.0, Parcel also supports "sideEffects": false , threrefore import { has } from 'lodash-es'; also is a tree shaking with the parcel. It also supports CommonJS tree modules, although it is more likely that shaking ES modules is more efficient than CommonJS, according to my experiment .

+40
Jun 02 '18 at 11:59
source share

If you are using babel, you should check babel-plugin-lodash , it will be cherry - choose the parts of lodash that you use for you, less hassle and less package.

It has several limitations :

  • You must use ES2015 import to download Lodash
  • Babel <6 & Node.js <4 arent supported
  • Chaining sequences are supported. See this blog post for alternatives.
  • Modular Package Support
+1
Jan 06 '18 at 20:05
source share

Import specific methods inside curly braces

 import { map, tail, times, uniq } from 'lodash'; 

Pros:

  • Only one import line (for a decent amount of functions)
  • More readable use: map () instead of _.map () later in javascript code.

Minuses:

  • Every time we want to use a new function or stop using another - it needs to be maintained and managed
0
Feb 13 '19 at 7:12
source share
0
May 7 '19 at 11:38
source share



All Articles