如何导入单个Lodash功能? [英] How to Import a Single Lodash Function?
问题描述
使用webpack,我正在尝试导入 isEqual ,因为 lodash
似乎正在导入所有内容。我尝试过以下操作但没有成功:
Using webpack, I'm trying to import isEqual since lodash
seems to be importing everything. I've tried doing the following with no success:
import { isEqual } from 'lodash'
import isEqual from 'lodash/lang'
import isEqual from 'lodash/lang/isEqual'
import { isEqual } from 'lodash/lang'
import { isEqual } from 'lodash/lang'
推荐答案
您可以将 lodash.isequal
作为单个模块安装,而不安装整个 lodash 包,如下所示:
You can install lodash.isequal
as a single module without installing the whole lodash package like so:
npm install --save lodash.isequal
使用ECMAScript 5和CommonJS模块时,然后像这样导入:
When using ECMAScript 5 and CommonJS modules, you then import it like this:
var isEqual = require('lodash.isequal');
使用ES6模块,这将是:
Using ES6 modules, this would be:
import isEqual from 'lodash.isequal';
您可以在代码中使用它:
And you can use it in your code:
const obj1 = {username: 'peter'};
const obj2 = {username: 'peter'};
const obj3 = {username: 'gregory'};
isEqual(obj1, obj2) // returns true
isEqual(obj1, obj3) // returns false
资料来源: Lodash文件
导入后,您可以在代码中使用 isEqual
函数。请注意,如果您以这种方式导入它,它不是名为 _
的对象的一部分,因此您
不引用它使用 _。isEqual
,但直接使用 isEqual
。
After importing, you can use the isEqual
function in your code. Note that it is not a part of an object named _
if you import it this way, so you
don't reference it with _.isEqual
, but directly with isEqual
.
替代方案:使用 lodash-es
Alternative: Using lodash-es
正如@kimamula :
使用webpack 4和 lodash-es 4.17.7及更高版本,此代码有效。
With webpack 4 and lodash-es 4.17.7 and higher, this code works.
import { isEqual } from 'lodash-es';
这是因为webpack 4支持 sideEffects flag和 lodash-es
4.17.7及更高版本包括标志(设置为 false
)。
This is because webpack 4 supports the sideEffects flag and lodash-es
4.17.7 and higher includes the flag (which is set to false
).
为什么不使用带斜线的版本?
此问题的其他答案表明您也可以使用短划线而不是点,如下所示:
Why Not Use the Version With the Slash? Other answers to this question suggest that you can also use a dash instead of a dot, like so:
import isEqual from 'lodash/isequal';
这也有效,但有两个小缺点:
This works, too, but there are two minor drawbacks:
- 你必须安装整个 lodash 包(
npm install --save lodash
),不只是小的单独的 lodash.isequal 包;存储空间很便宜且CPU很快,所以你可能不在乎这个 - 使用像webpack这样的工具时产生的捆绑包会稍微大些;我发现使用最小代码示例
isEqual
的捆绑包大小平均大28%(尝试过webpack 2和webpack 3,有或没有Babel,有或没有Uglify)
- You have to install the whole lodash package (
npm install --save lodash
), not just the small separate lodash.isequal package; storage space is cheap and CPUs are fast, so you may not care about this - The resulting bundle when using tools like webpack will be slightly bigger; I found out that bundle sizes with a minimal code example of
isEqual
are on average 28% bigger (tried webpack 2 and webpack 3, with or without Babel, with or without Uglify)
这篇关于如何导入单个Lodash功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!