在 Angular 项目中使用 lodash 时的优化救助警告

问题描述 投票:0回答:3

x 组件取决于“lodash”。 CommonJS 或 AMD 依赖项可以 导致优化救助。有关详细信息,请参阅: https://angular.io/guide/build#configuring-commonjs-dependencies

这就是我在 x component.ts 中使用 lodash 的方式

import * as _ from 'lodash';
....
....

foo(){
 this.myObject = _.mapValues(this.myObject , () => true);
}

如何摆脱这个警告?

angular typescript lodash
3个回答
4
投票

您可以使用 lodash-es(ES 模块化),而不是使用 lodash 的 CommonJS 变体。


1
投票

你也可以考虑完全不使用 lodash。从这篇文章 10 Lodash Features You Can Replace with ES6 我们有以下可以用 ES6 替换的特性

  1. 映射、过滤、减少

这些收集方法使数据转换变得轻而易举,并且几乎得到了普遍支持。我们可以将它们与箭头函数配对,以帮助我们为 Lodash 提供的实现编写简洁的替代方案:

_.map([1, 2, 3], function(n) { return n * 3; });
// [3, 6, 9]
_.reduce([1, 2, 3], function(total, n) { return total + n; }, 0);
// 6
_.filter([1, 2, 3], function(n) { return n <= 2; });
// [1, 2]

// becomes

[1, 2, 3].map(n => n * 3);
[1, 2, 3].reduce((total, n) => total + n);
[1, 2, 3].filter(n => n <= 2);

也不止于此。如果我们使用的是现代浏览器,我们也可以使用

find
some
every
reduceRight

  1. 头和尾

解构语法允许我们在没有实用函数的情况下获得列表的头部和尾部

_.head([1, 2, 3]);
// 1
_.tail([1, 2, 3]);
// [2, 3]

// becomes

const [head, ...tail] = [1, 2, 3];

也可以用类似的方式获取初始元素和最后一个元素:

_.initial([1, 2, 3]);
// -> [1, 2]
_.last([1, 2, 3]);
// 3

// becomes

const [last, ...initial] = [1, 2, 3].reverse();

如果你觉得反向改变数据结构很烦人,那么你可以在调用反向之前使用扩展运算符克隆数组:

const xs = [1, 2, 3];
const [last, ...initial] = [...xs].reverse();
  1. 休息和传播

rest
spread
函数允许我们定义和调用接受可变数量参数的函数。 ES6 为这两种操作引入了专用语法:

var say = _.rest(function(what, names) {
  var last = _.last(names);
  var initial = _.initial(names);
  var finalSeparator = (_.size(names) > 1 ? ', & ' : '');
  return what + ' ' + initial.join(', ') +
    finalSeparator + _.last(names);
});

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"

// becomes

const say = (what, ...names) => {
  const [last, ...initial] = names.reverse();
  const finalSeparator = (names.length > 1 ? ', &' : '');
  return `${what} ${initial.join(', ')} ${finalSeparator} ${last}`;
};

say('hello', 'fred', 'barney', 'pebbles');
// "hello fred, barney, & pebbles"
  1. 咖喱

如果没有像

[TypeScript][5]
[Flow][6]
这样的高级语言,我们就不能给我们的函数类型签名,这使得柯里化变得非常困难。当我们收到柯里化函数时,很难知道已经提供了多少参数,接下来我们需要提供哪些参数。使用箭头函数,我们可以显式定义柯里化函数,让其他程序员更容易理解它们:

function add(a, b) {
  return a + b;
}
var curriedAdd = _.curry(add);
var add2 = curriedAdd(2);
add2(1);
// 3

// becomes

const add = a => b => a + b;
const add2 = add(2);
add2(1);
// 3

这些明确柯里化的箭头函数对于调试特别重要:

var lodashAdd = _.curry(function(a, b) {
  return a + b;
});
var add3 = lodashAdd(3);
console.log(add3.length)
// 0
console.log(add3);
// function (a, b) {
// /* [wrapped with _.curry & _.partial] */
//   return a + b;
// }

// becomes

const es6Add = a => b => a + b;
const add3 = es6Add(3);
console.log(add3.length);
// 1
console.log(add3);
// function b => a + b

如果我们使用像

lodash/fp
ramda
这样的函数库,我们也可以使用箭头来消除对自动咖喱样式的需要:

_.map(_.prop('name'))(people);

// becomes

people.map(person => person.name);
  1. 部分

与柯里化一样,我们可以使用箭头函数使部分应用变得简单和明确:

var greet = function(greeting, name) {
  return greeting + ' ' + name;
};

var sayHelloTo = _.partial(greet, 'hello');
sayHelloTo('fred');
// "hello fred"

// becomes

const sayHelloTo = name => greet('hello', name);
sayHelloTo('fred');
// "hello fred"

也可以将剩余参数与扩展运算符一起使用以部分应用可变参数函数:

const sayHelloTo = (name, ...args) => greet('hello', name, ...args);
sayHelloTo('fred', 1, 2, 3);
// "hello fred"
  1. 运营商

Lodash 附带了一些函数,将语法运算符重新实现为函数,以便将它们传递给集合方法。

在大多数情况下,箭头函数使它们足够简单和简短,我们可以将它们定义为内联:

_.eq(3, 3);
// true
_.add(10, 1);
// 11
_.map([1, 2, 3], function(n) {
  return _.multiply(n, 10);
});
// [10, 20, 30]
_.reduce([1, 2, 3], _.add);
// 6

// becomes

3 === 3
10 + 1
[1, 2, 3].map(n => n * 10);
[1, 2, 3].reduce((total, n) => total + n);
  1. 路径

Lodash 的许多函数都将路径作为字符串或数组。我们可以使用箭头函数来创建更多可重用的路径:

var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };

_.at(object, ['a[0].b.c', 'a[1]']);
// [3, 4]
_.at(['a', 'b', 'c'], 0, 2);
// ['a', 'c']

// becomes

[
  obj => obj.a[0].b.c,
  obj => obj.a[1]
].map(path => path(object));

[
  arr => arr[0],
  arr => arr[2]
].map(path => path(['a', 'b', 'c']));

因为这些路径“只是函数”,我们也可以组合它们:

const getFirstPerson = people => people[0];
const getPostCode = person => person.address.postcode;
const getFirstPostCode = people => getPostCode(getFirstPerson(people));

我们甚至可以创建接受参数的高阶路径:

const getFirstNPeople = n => people => people.slice(0, n);

const getFirst5People = getFirstNPeople(5);
const getFirst5PostCodes = people => getFirst5People(people).map(getPostCode);
  1. 选择

pick 实用程序允许我们从目标对象中选择我们想要的属性。我们可以使用解构和速记对象字面量来获得相同的结果:

var object = { 'a': 1, 'b': '2', 'c': 3 };

return _.pick(object, ['a', 'c']);
// { a: 1, c: 3 }

// becomes

const { a, c } = { a: 1, b: 2, c: 3 };

return { a, c };
  1. 常数,身份,Noop

Lodash 提供了一些用于创建具有特定行为的简单函数的实用程序:

_.constant({ 'a': 1 })();
// { a: 1 }
_.identity({ user: 'fred' });
// { user: 'fred' }
_.noop();
// undefined

我们可以使用箭头内联定义所有这些函数:

const constant = x => () => x;
const identity = x => x;
const noop = () => undefined;

或者我们可以重写上面的例子如下:

(() => ({ a: 1 }))();
// { a: 1 }
(x => x)({ user: 'fred' });
// { user: 'fred' }
(() => undefined)();
// undefined
  1. 链接与流

Lodash 提供了一些函数来帮助我们编写链式语句。在许多情况下,内置的集合方法返回一个可以直接链接的数组实例,但在某些情况下,方法会改变集合,这是不可能的。

但是,我们可以定义与箭头函数数组相同的转换:

_([1, 2, 3])
 .tap(function(array) {
   // Mutate input array.
   array.pop();
 })
 .reverse()
 .value();
// [2, 1]

// becomes

const pipeline = [
  array => { array.pop(); return array; },
  array => array.reverse()
];

pipeline.reduce((xs, f) => f(xs), [1, 2, 3]);
This way, we don’t even have to think about the difference between tap and thru. Wrapping this reduction in a utility function makes a great general purpose tool:

const pipe = functions => data => {
  return functions.reduce(
    (value, func) => func(value),
    data
  );
};

const pipeline = pipe([
  x => x * 2,
  x => x / 3,
  x => x > 5,
  b => !b
]);

pipeline(5);
// true
pipeline(20);
// false

结论

Lodash 仍然是一个很棒的库,本文只是提供了一个全新的视角,说明 JavaScript 的进化版本如何让我们解决以前依赖实用程序模块的一些问题。
不要忽视它。取而代之的是,下次您进行抽象时,请考虑一个简单的函数是否可以代替!


0
投票

以下解决方案对我有用:

第一步:

npm install --save lodash-es

第 2 步:将 CommonJS 依赖列入白名单 -

angular.json

"architect": {
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "allowedCommonJsDependencies": ["lodash"]
    }
  }
}

在这里找到更多细节:https://angular.io/guide/build#configuring-commonjs-dependencies

© www.soinside.com 2019 - 2024. All rights reserved.