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



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);
}

如何摆脱此警告?

与其使用lodash 的 CommonJS 变体,不如使用 lodash-es(ES modulized)。

你也可以考虑根本不使用 lodash。从这篇文章中,您可以用 ES6 替换 10 个 Lodash 功能,我们有以下功能,您可以用 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);

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

  1. Head & Tail

解构语法允许我们在没有实用程序函数的情况下获取列表的正面和反面

_.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();

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

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

restspread函数允许我们定义和调用接受可变数量参数的函数。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],我们就不能给我们的函数类型签名,这使得 curry 相当困难。当我们收到柯里函数时,很难知道已经提供了多少参数,以及我们接下来需要提供哪些参数。使用箭头函数,我们可以显式定义柯里函数,使其他程序员更容易理解它们:

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/fpramda这样的函数库,我们还可以使用箭头来消除对自动咖喱样式的需求:

_.map(_.prop('name'))(people);
// becomes
people.map(person => person.name);
  1. 部分

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

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"

也可以将 rest 参数与展开运算符一起使用,以部分应用可变参数函数:

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. >Chaining & Flow

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 的进化版本如何允许我们在以前依赖实用程序模块的情况下解决一些问题.
不要忽视它。相反,下次你进行抽象时,想想一个简单的函数是否可以代替!

以下解决方案对我有用:

第 1 步: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

最新更新