简体   繁体   English

导入lodash的正确方法

[英]Correct way to import lodash

I had a pull request feedback below, just wondering which way is the correct way to import lodash?我在下面有一个 pull request 反馈,只是想知道哪种方式是导入 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.你最好从 'lodash/has' 导入 has。对于早期版本的 lodash (v3) 本身就很重,我们应该只导入一个特定的模块/函数,而不是导入整个 lodash 库。 Not sure about the newer version (v4).不确定较新的版本 (v4)。

import has from 'lodash/has';

vs对比

import { has } from 'lodash';

Thanks谢谢

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.更好,因为 lodash 将它的所有函数保存在一个文件中,所以与其以 100k 的大小导入整个 'lodash' 库,最好只导入 lodash 的has函数,它可能是 2k。

If you are using webpack 4 , the following code is tree shakable.如果你使用的是webpack 4 ,下面的代码是 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). CommonJS 模块不可摇树,所以你绝对应该使用lodash-es ,它是作为 ES 模块导出的 Lodash 库,而不是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 ). lodash-es的 package.json 包含"sideEffects": false ,它通知 webpack 4 包内的所有文件都没有副作用(参见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.此信息对于 treeShaking 至关重要,因为模块捆绑器不会对可能包含副作用的文件进行 treeshake,即使其导出的成员未在任何地方使用。

Edit编辑

As of version 1.9.0, Parcel also supports "sideEffects": false , threrefore import { has } from 'lodash-es'; 从 1.9.0 版本开始,Parcel 还支持"sideEffects": false ,因此import { has } from 'lodash-es'; is also tree shakable with Parcel.也可以用 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 .它还支持摇树 CommonJS 模块,尽管根据我的实验,ES 模块的摇树可能比 CommonJS 更有效。

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.更易读的用法:稍后在 javascript 代码中使用 map() 而不是 _.map() 。

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.复制自: The Correct Way to Import Lodash Libraries - 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.如果你正在使用 babel,你应该查看babel-plugin-lodash ,它会挑选你正在使用的 lodash 的部分,减少麻烦和更小的包。

It has a few limitations :它有一些限制

  • You must use ES2015 imports to load Lodash您必须使用 ES2015 导入来加载 Lodash
  • Babel < 6 & Node.js < 4 aren't supported不支持 Babel < 6 和 Node.js < 4
  • Chain sequences aren't supported.不支持链序列。 See this blog post for alternatives.有关替代方案,请参阅此博客文章
  • Modularized method packages aren't supported不支持模块化方法包

I just put them in their own file and export it for node and webpack:我只是将它们放在自己的文件中,然后将其导出到 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'),
}

I think this answer can be used in any project easily and brings the best result with less effort.我认为这个答案可以轻松地用于任何项目,并以更少的努力带来最佳结果。

For Typescript users, use as following :对于打字稿用户,使用如下:

// lodash.utils.ts
export { default as get } from 'lodash/get';
export { default as isEmpty } from 'lodash/isEmpty';
export { default as isNil } from 'lodash/isNil';
...

And can be used the same way as importing lodash :并且可以像导入 lodash 一样使用:

//some-code.ts
import { get } from './path/to/lodash.utils'

export static function getSomething(thing: any): any {
    return get(thing, 'someSubField', 'someDefaultValue')
}

Or if you prefer to keep the _ to avoid conflicts (ex. map from rxjs vs lodash )或者如果你喜欢保持_以避免冲突(例如: maprxjs VS lodash

//some-other-code.ts
import * as _ from './path/to/lodash.utils'

export static function getSomething(thing: any): any {
    return _.get(thing, 'someSubField', 'someDefaultValue')
}

UPDATE : Seems like the right way to export is :更新:似乎正确的导出方式是:

export * as get from 'lodash/get';
export * as isEmpty from 'lodash/isEmpty';
export * as isNil from 'lodash/isNil';
...

But there is a weird collision with @types/lodash , I've removed this type package because I would get this error :但是与@types/lodash有一个奇怪的冲突,我已经删除了这个类型包,因为我会得到这个错误:

Module '"/../project/node_modules/@types/lodash/cloneDeep"' uses 'export =' and cannot be used with 'export *'.ts(2498)模块 '"/../project/node_modules/@types/lodash/cloneDeep"' 使用 'export =' 并且不能与 'export *'.ts(2498) 一起使用

I think the more cleaner way of importing lodash is just like this:-我认为更简洁的导入 lodash 的方式是这样的:-

import _ from 'lodash'从'lodash'导入_

then you can use what ever you want just by using this underscore just like this:-然后你可以像这样使用这个下划线来使用你想要的任何东西:-

_.has() _。已()

For those who want to keep using _ , then just import them like this:对于那些想要继续使用 _ 的人,只需像这样导入它们:

import groupBy from 'lodash/groupBy';
import filter from 'lodash/filter';
import get from 'lodash/get';

window._ = {groupBy, filter, get};

import { cloneDeep, groupBy } from 'lodash';

I think this is simpler when you don't need to convert array to lodash object by using _.我认为当您不需要使用 _ 将数组转换为 lodash object 时,这会更简单。

const groupData = groupBy(expandedData, (x) => x.room.name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM