Correct way to import lodash

2019-01-12 23:43发布

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

You'd better do import has from 'lodash/has'.. For the earlier version of lodash (v3) which by itself is pretty heavy, we should only import a specidic module/function rather than importing the whole lodash library. Not sure about the newer version (v4).

import has from 'lodash/has';

vs

import { has } from 'lodash';

Thanks

3条回答
▲ chillily
2楼-- · 2019-01-13 00:06

If you are using webpack 4, the following code is tree shakable.

import { has } from 'lodash-es';

The points to note;

  1. 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).

  2. 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).

  3. 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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-13 00:22

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.

查看更多
别忘想泡老子
4楼-- · 2019-01-13 00:25

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:

  • You must use ES2015 imports to load Lodash
  • Babel < 6 & Node.js < 4 aren’t supported
  • Chain sequences aren’t supported. See this blog post for alternatives.
  • Modularized method packages aren’t supported
查看更多
登录 后发表回答