Javascript 如何导入单个 Lodash 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43479464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:57:24  来源:igfitidea点击:

How to Import a Single Lodash Function?

javascriptlodash

提问by adang3

Using webpack, I'm trying to import isEqualsince lodashseems to be importing everything. I've tried doing the following with no success:

使用 webpack,我试图导入isEqual,因为lodash似乎正在导入所有内容。我尝试执行以下操作但没有成功:

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'

回答by Patrick Hund

You can install lodash.isequalas a single module without installing the whole lodashpackage like so:

您可以lodash.isequal作为单个模块安装,而无需安装整个lodash包,如下所示:

npm install --save lodash.isequal

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

当使用 ECMAScript 5 和 CommonJS 模块时,你可以像这样导入它:

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

Using ES6 modules, this would be:

使用 ES6 模块,这将是:

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

来源:Lodash 文档

After importing, you can use the isEqualfunction in your code. Note that it is not a part of an object named _if you import it this way, so you don'treference it with _.isEqual, but directly with isEqual.

导入后,您可以isEqual在代码中使用该函数。请注意,_如果您以这种方式导入它,则它不是命名对象的一部分,因此您 不使用引用它_.isEqual,而是直接使用isEqual.

Alternative: Using lodash-es

替代方案:使用 lodash-es

As pointed out by @kimamula:

正如@kimamula所指出的:

With webpack 4 and lodash-es4.17.7 and higher, this code works.

使用 webpack 4 和lodash-es4.17.7 及更高版本,此代码有效。

import { isEqual } from 'lodash-es';

This is because webpack 4 supports the sideEffectsflag and lodash-es4.17.7 and higher includes the flag (which is set to false).

这是因为 webpack 4 支持sideEffects标志并且lodash-es4.17.7 及更高版本包含该标志(设置为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 lodashpackage (npm install --save lodash), not just the small separate lodash.isequalpackage; 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 isEqualare on average 28% bigger (tried webpack 2 and webpack 3, with or without Babel, with or without Uglify)
  • 您必须安装整个lodash包 ( npm install --save lodash),而不仅仅是单独的lodash.isequal包;存储空间便宜,CPU 速度快,所以你可能不关心这个
  • 使用 webpack 等工具生成的包会稍微大一些;我发现使用最小代码示例的包大小isEqual平均大 28%(尝试了 webpack 2 和 webpack 3,有或没有 Babel,有或没有 Uglify)

回答by Jo Sprague

If you just want to include isEqualand not the rest of the lodashfunctions (useful for keeping your bundle size small), you can do this in ES6;

如果你只是想包含isEqual而不是其他的lodash函数(对于保持你的包很小),你可以在 ES6 中做到这一点;

import isEqual from 'lodash/isEqual'

This is pretty much the same as what's described in the lodashREADME, except that there they use require()syntax.

lodashREADME 中描述的几乎相同,只是它们使用require()语法。

var at = require('lodash/at');

回答by kimamula

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

使用 webpack 4 和 lodash-es 4.17.7 及更高版本,此代码有效。

import { isEqual } from 'lodash-es';

This is because webpack 4 supports sideEffectsflagand lodash-es 4.17.7 and higher includes the flag (which is set to false).

这是因为 webpack 4 支持sideEffects标志和 lodash-es 4.17.7 及更高版本包括标志(设置为false)。

Edit

编辑

As of version 1.9.0, Parcel also supports "sideEffects": false, threrefore import { isEqual } from 'lodash-es';is also tree shakable with Parcel.

从 1.9.0 版本开始,Parcel 也支持"sideEffects": false,因此import { isEqual } from 'lodash-es';也可以使用 Parcel 进行 tree shakable。

回答by Alex Beauchemin

Not related to webpack but I'll add it here as a lot of people are currently moving to typescript.

与 webpack 无关,但我会在这里添加它,因为很多人目前正在转向打字稿。

You can also import a single function from lodash using import isEqual from 'lodash/isEqual';in typescript with the esModuleInteropflag in the compiler options (tsconfig.json)

您还可以import isEqual from 'lodash/isEqual';在打字稿中使用带有esModuleInterop编译器选项 (tsconfig.json) 中的标志的lodash 导入单个函数

example

例子

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "lib": ["es6", "dom"],
    "moduleResolution": "node",
    "esModuleInterop": true,
    ...
  }
}

回答by mlunoe

Lodash lists a couple of options in their README:

Lodash 在他们的README 中列出了几个选项:

  • babel-plugin-lodash

    • Install lodash and the babel plugin:
    $ npm i --save lodash
    $ npm i --save-dev babel-plugin-lodash @babel/cli @babel/preset-env
    
    • Add this to your .babelrc
    {
      "plugins": ["lodash"],
      "presets": [["@babel/env", { "targets": { "node": 6 } }]]
    }
    
    • Transforms this
    import _ from 'lodash'
    import { add } from 'lodash/fp'
    
    const addOne = add(1)
    _.map([1, 2, 3], addOne)
    

    Roughly to this:

    import _add from 'lodash/fp/add'
    import _map from 'lodash/map'
    
    const addOne = _add(1)
    _map([1, 2, 3], addOne)
    
  • lodash-webpack-plugin

    • Install lodash and webpack plugin:
    $ npm i --save lodash
    $ npm i --save-dev lodash-webpack-plugin babel-core babel-loader babel-plugin-lodash babel-preset-env webpack
    
    • Configure your webpack.config.js:
    var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
    var webpack = require('webpack');
    
    module.exports = {
      'module': {
        'rules': [{
          'use': 'babel-loader',
          'test': /\.js$/,
          'exclude': /node_modules/,
          'options': {
            'plugins': ['lodash'],
            'presets': [['env', { 'modules': false, 'targets': { 'node': 4 } }]]
          }
        }]
      },
      'plugins': [
        new LodashModuleReplacementPlugin,
        new webpack.optimize.UglifyJsPlugin
      ]
    };
    
  • lodash-esusing the lodash cli

    • $ lodash modularize exports=es -o ./
  • babel-plugin-lodash

    • 安装 lodash 和 babel 插件:
    $ npm i --save lodash
    $ npm i --save-dev babel-plugin-lodash @babel/cli @babel/preset-env
    
    • 将此添加到您的 .babelrc
    {
      "plugins": ["lodash"],
      "presets": [["@babel/env", { "targets": { "node": 6 } }]]
    }
    
    • 改变这个
    import _ from 'lodash'
    import { add } from 'lodash/fp'
    
    const addOne = add(1)
    _.map([1, 2, 3], addOne)
    

    大致是这样的:

    import _add from 'lodash/fp/add'
    import _map from 'lodash/map'
    
    const addOne = _add(1)
    _map([1, 2, 3], addOne)
    
  • lodash-webpack-plugin

    • 安装 lodash 和 webpack 插件:
    $ npm i --save lodash
    $ npm i --save-dev lodash-webpack-plugin babel-core babel-loader babel-plugin-lodash babel-preset-env webpack
    
    • 配置您的webpack.config.js
    var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
    var webpack = require('webpack');
    
    module.exports = {
      'module': {
        'rules': [{
          'use': 'babel-loader',
          'test': /\.js$/,
          'exclude': /node_modules/,
          'options': {
            'plugins': ['lodash'],
            'presets': [['env', { 'modules': false, 'targets': { 'node': 4 } }]]
          }
        }]
      },
      'plugins': [
        new LodashModuleReplacementPlugin,
        new webpack.optimize.UglifyJsPlugin
      ]
    };
    
  • 使用 lodash cli 的lodash-es

    • $ lodash modularize exports=es -o ./

回答by Ollie Williams

import { isEqual } from 'lodash-es';is importing the entire library. I am using Rollup which should do tree shaking by default.

import { isEqual } from 'lodash-es';正在导入整个库。我正在使用 Rollup,默认情况下它应该做树摇动。

Whenever I've written my own modules, this named import syntax works and Rollup successfully tree shakes, so I'm a bit confused as to why it won't work with Lodash.

每当我编写自己的模块时,这个命名的导入语法都有效并且 Rollup 成功地进行了树抖动,所以我有点困惑为什么它不能与 Lodash 一起使用。

回答by viktorko99

this actually worked for me

这实际上对我有用

import { isEqual } from 'lodash';