Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

javascript - How to Import a Single Lodash Function?

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can install lodash.isequal as a single module without installing the whole lodash package like so:

npm install --save lodash.isequal

When using ECMAScript 5 and CommonJS modules, you then import it like this:

var isEqual = require('lodash.isequal');

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

Source: Lodash documentation

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.

Alternative: Using lodash-es

As pointed out by @kimamula:

With webpack 4 and lodash-es 4.17.7 and higher, this code works.

import { isEqual } from 'lodash-es';

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:

  • 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...