在 Angular中 使用 Lodash 的方法
如何Lodash 是 JavaScript 很有名的 package,尤其對於處理 array 很有一套,Angular 該如何使用 lodash 呢 ? 這也可以視為在 Angular 使用傳統 JavaScript package 的 SOP。
Version
Node.js 8.9.4
Angular CLI 1.6.2
Angular 5.2.2
安裝 Lodash
~/MyProject $ npm install lodash --save
使用 npm 安裝 lodash 。
安裝 Lodash Type 定義檔
~/MyProject $ npm install @types/lodash --save-dev
傳統 JavaScript 並沒有型別,但 TypeScript 是個強型別語言,除了型別外還有泛型,這該怎麼與傳統 JavaScript 搭配呢 ?
TypeScript 的解決方案是另外使用 *.d.ts ,此為 type 定義檔。
一般來說,若是知名的 JavaScript library,都已經有人維護 type 定義檔,其 package 的規則是 @types/package 。
由於 type 定義檔只是 TypeScript 編譯使用,以此加上 --save-dev 。
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"types" : ["lodash"],
"lib": [
"es2017",
"dom"
]
}
}
14 行
"types" : ["lodash"],
在 typeRoots 新增 types ,在陣列中加入 lodash ,表示 TypeScript 在編譯時會使用剛剛安裝的 lodash type 定義檔。
Import Lodash
app.component.ts
import {Component, OnInit} from '@angular/core';
import * as _ from 'lodash';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
ngOnInit(): void {
const scores: number[] = [100, 99, 98];
_.remove(scores, 2);
scores.forEach((score) => console.log(score));
}
}
第 2 行
import * as _ from 'lodash';
載入 lodash 。
因為 lodash 習慣以 _ 使用,因此 import 時特別取別名為 _
WebStorm 對於 Angular 內建的 API,都可以自動 import,但對於 JavaScript 的 package,目前 WebStorm 還沒有辦法自動 import,需手動載入
15 行
_.remove(scores, 2);
陣列的移除元素一直是 JavaScript 比較麻煩的部分,透過 lodash 的 remove() ,可以很簡單的使用。
Conclusion
實務上若有 Angular 版本的 package,當然優先使用;若遇到必須使用 JavaScript package 不可的場合,除了安裝 package 外,還要安裝 type 定義檔,並且在 tsconfig.json 設定,如此才可以在 Angular 正確使用並通過編譯
Sample Code
完整的範例可以在我的GitHub 上找到
总结
以上所述是小编给大家介绍的在 Angular中 使用 Lodash 的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
相关文章
AngularJS 将再发布一个重要版本 然后进入长期支持阶段
目前团队正在开发 AngularJS 1.7.0,而 1.7 的开发周期将一直持续到 2018 年 6 月 30 日2018-01-01
Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解
这篇文章主要为大家介绍了Angular依赖注入系统里Injection token PLATFORM_ID使用场景详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-11-11
Angular2中Bootstrap界面库ng-bootstrap详解
不知道大家有没有留意,最近angular-ui团队终于正式发布了基于 Angular2的Bootstrap界面库ng-bootstrap ,之前工作中一直在用 AngularJS 1.x 的UI Bootstrap , 因此对这个ng-bootstrap 也是很感兴趣,所以第一时间进行试用。这篇文章就给大家详细介绍下ng-bootstrap。2016-10-10
AngularJs Understanding the Controller Component
本文主要介绍AngularJs Understanding the Controller Component的内容,这里整理了相关资料,及简单示例代码,有兴趣的小伙伴可以参考下2016-09-09
Angular应用里环境变量SERVER_REQUEST_ORIGIN含义解析
这篇文章主要为大家介绍了Angular应用里环境变量SERVER_REQUEST_ORIGIN的含义解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10


最新评论