我有一个拉请求反馈下面,只是想知道哪种方式是导入lodash的正确方式?

你最好从'lodash/has'导入has ..对于早期版本 lodash (v3)本身就很重,我们应该只导入 一个特殊的模块/函数,而不是导入整个lodash 图书馆。不确定更新的版本(v4)。

import has from 'lodash/has';

vs

import { has } from 'lodash';

谢谢


当前回答

我只是把它们放在自己的文件中,然后导出给node和webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

其他回答

您可以导入它们为

import {concat, filter, orderBy} from 'lodash';

或者是

import concat from 'lodash/concat';
import orderBy from 'lodash/orderBy';
import filter from 'lodash/filter';

第二个比第一个优化得多,因为它只加载所需的模块

然后像这样使用

pendingArray: concat(
                    orderBy(
                        filter(payload, obj => obj.flag),
                        ['flag'],
                        ['desc'],
                    ),
                    filter(payload, obj => !obj.flag),

如果你正在使用babel,你应该检查babel-plugin-lodash,它会挑选你正在使用的lodash的部分,更少的麻烦和更小的捆绑。

它有一些局限性:

你必须使用ES2015导入来加载Lodash 不支持Babel < 6 & Node.js < 4 不支持链序列。请参阅这篇博客文章以获得替代方案。 不支持模块化的方法包

如果你正在使用webpack 4,下面的代码是可摇树的。

import { has } from 'lodash-es';

注意事项;

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

从1.9.0版本开始,Parcel还支持"sideEffects": false,因此从'lodash-es'导入{has};也是摇树与包裹。 它还支持CommonJS模块的摇树,尽管根据我的实验,ES模块的摇树可能比CommonJS更有效。

Import has from 'lodash/has';更好,因为lodash在一个文件中保存了它所有的函数,所以与其在100k导入整个'lodash'库,不如只导入lodash的has函数,它可能是2k。

我只是把它们放在自己的文件中,然后导出给node和webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}