手把手教你搭建自己的Angular元件庫 - DevUI

DevUI團隊發表於2021-04-25

摘要:DevUI 是一款面向企業中後臺產品的開源前端解決方案,它倡導沉浸靈活至簡的設計價值觀,提倡設計者為真實的需求服務,為多數人的設計,拒絕譁眾取寵、取悅眼球的設計。如果你正在開發 ToB工具類產品,DevUI 將是一個很不錯的選擇!

 

DevUI是一支兼具設計視角和工程視角的團隊,服務於華為雲DevCloud平臺和華為內部數箇中後臺系統,服務於設計師和前端工程師。
官方網站:devui.design
Ng元件庫:ng-devui(歡迎Star)

引言

作為前端開發者,隨著公司業務的不斷髮展和增長,業務對元件功能、互動的訴求會越來越多,不同產品或者團隊之間公用的元件也會越來越多,這時候就需要有一套用於支撐內部使用的元件庫,也可以是基於已有元件擴充套件或者封裝一些原生三方庫。本文會手把手教你搭建自己的Angular元件庫。

建立元件庫

我們首先建立一個Angular專案,用來管理元件的展示和釋出,用以下命令生成一個新的專案

ng new <my-project>

 


專案初始化完成後,進入到專案下執行以下cli命令初始化lib目錄和配置, 生成一個元件庫骨架

ng generate library <my-lib> --prefix <my-prefix>

 


my-lib為自己指定的library名稱,比如devui,my-prefix為元件和指令字首,比如d-xxx,預設生成的目錄結構如下

手把手教你搭建自己的Angular元件庫 - DevUI

angular.json配置檔案中也可以看到projects下面多出了一段專案型別為library的配置

"my-lib": {
  "projectType": "library",
  "root": "projects/my-lib",
  "sourceRoot": "projects/my-lib/src",
  "prefix": "dev",
  "architect": {
    "build": {
      "builder": "@angular-devkit/build-ng-packagr:build",
      "options": {
          "tsConfig": "projects/my-lib/tsconfig.lib.json",
          "project": "projects/my-lib/ng-package.json"
      },
  "configurations": {
    "production": {
      "tsConfig": "projects/my-lib/tsconfig.lib.prod.json"
    }
  }
},
...

 

關鍵配置修改

目錄佈局調整

從目錄結構可以看出預設生成的目錄結構比較深,參考material design,我們對目錄結構進行自定義修改如下:

手把手教你搭建自己的Angular元件庫 - DevUI

修改說明:

  • 刪除了my-lib目錄下的src目錄,把src目錄下的test.ts拷貝出來,元件庫測試檔案入口
  • 把元件平鋪到my-lib目錄下,並在my-lib目錄下新增my-lib.module.ts(用於管理元件的匯入、匯出)和index.ts(匯出my-lib.module.ts,簡化匯入)
  • 修改angular.json中my-lib下面的sourceRoot路徑,指向my-lib即可

修改如下:

// my-lib.module.ts


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AlertModule } from 'my-lib/alert'; // 此處按照按需引入方式匯入,my-lib對應我們的釋出庫名


@NgModule({
  imports: [ CommonModule ],
  exports: [AlertModule],
  providers: [],
})
export class MyLibModule {}


// index.ts
export * from './my-lib.module';


//angular.json
"projectType": "library",
"root": "projects/my-lib",
"sourceRoot": "projects/my-lib", // 這裡路徑指向我們新的目錄
"prefix": "devui"

 

庫構建關鍵配置

ng-package.json配置檔案,angular library構建時依賴的配置檔案

{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../publish",
  "lib": {
    "entryFile": "./index.ts"
  },
  "whitelistedNonPeerDependencies": ["lodash-es"]
}

 

關鍵配置說明:

  • dest,lib構建輸出路徑,這裡我們修改為publish目錄,和專案構建dist目錄區分開
  • lib/entryFile,指定庫構建入口檔案,此處指向我們上文的index.ts

whitelistedNonPeerDependencies(可選),如果元件庫依賴了第三方庫,比如lodash,需要在此處配置白名單,因為ng-packagr構建時為了避免第三方依賴庫可能存在多版本衝突的風險,會檢查package.json的dependencies依賴配置,如果不配置白名單,存在dependencies配置時就會構建失敗。

package.json配置,建議儘量使用peerDependcies,如果業務也配置了相關依賴項的話

{
  "name": "my-lib",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "^9.1.6",
    "@angular/core": "^9.1.6",
    "tslib": "^1.10.0"
  }
}

 

詳細完整的配置,可以參考angular官方文件 https://github.com/ng-packagr/ng-packagr/blob/master/docs/DESIGN.md

開發一個Alert元件

元件功能介紹

我們參考DevUI元件庫的alert元件開發一個元件,用來測試我們的元件庫,alert元件主要是根據使用者傳入的型別呈現不同的顏色和圖示,用於向使用者顯示不同的警告資訊。視覺顯示如下

手把手教你搭建自己的Angular元件庫 - DevUI

元件結構分解

首先,我們看一下alert元件目錄包含哪些檔案

手把手教你搭建自己的Angular元件庫 - DevUI

目錄結構說明:

  • 元件是一個完整的module(和普通業務模組一樣),幷包含了一個單元測試檔案
  • 元件目錄下有一個package.json,用於支援二級入口(單個元件支援按需引入)
  • public-api.ts用於匯出module、元件、service等,是對外暴露的入口,index.ts會匯出public-api,方便其它模組

關鍵內容如下:

// package.json
{
  "ngPackage": {
    "lib": {
      "entryFile": "public-api.ts"
    }
  }
}


//public-api.ts
/*
* Public API Surface of Alert
*/
export * from './alert.component';
export * from './alert.module';

 

定義輸入輸出

接下來我們就開始實現元件,首先我們定義一下元件的輸入輸出,alert內容我們採用投影的方式傳入,Input引數支援指定alert型別、是否顯示圖示、alert是否可關閉,Output返回關閉回撥,用於使用者處理關閉後的邏輯

import { Component, Input } from '@angular/core';
// 定義alert有哪些可選型別
export type AlertType = 'success' | 'danger' | 'warning' | 'info';


@Component({
  selector: 'dev-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss'],
})
export class AlertComponent {
  // Alert 型別
  @Input() type: AlertType = 'info';
  // 是否顯示圖示,用於支援使用者自定義圖示
  @Input() showIcon = true;
  // 是否可關閉
  @Input() closeable = false;
  // 關閉回撥
  @Output() closeEvent: EventEmitter<boolean> = new EventEmitter<boolean>();
  hide = false;
  constructor() {}


  close(){
    this.closeEvent.emit(true);
    this.hide = true;
  }
}

 

定義佈局

根據api定義和視覺顯示我們來實現頁面佈局結構,佈局包含一個關閉按鈕、圖示占位和內容投影 ,元件關閉時,我們採用清空dom的方式處理。

<div class="dev-alert {{ type }} " *ngIf="!hide">
  <button type="button" class="dev-close" (click)="close()" *ngIf="closeable"></button>
  <span class="dev-alert-icon icon-{{ type }}" *ngIf="showIcon"></span>
  <ng-content></ng-content>
</div>

 

到這裡,我們元件的頁面佈局和元件邏輯已經封裝完成,根據視覺顯示再加上對應的樣式處理就開發完成了。

測試Alert元件

開發態引用元件

元件開發過程中,我們需要能夠實時除錯邏輯和調整UI展示,開啟根目錄下的tsconfig.json,修改一下paths路徑對映,方便我們在開發態就可以本地除錯我們的元件,這裡直接把my-lib指向了元件原始碼,當然也可以通過ng build my-lib --watch來使用預設的配置, 指向構建好的預釋出檔案,此時這裡就要配置成我們修改過的目錄public/my-lib/*

"paths": {
  "my-lib": [
    "projects/my-lib/index.ts"
  ],
  "my-lib/*": [
    "projects/my-lib/*"
  ],
}

 

配置完成後,就可以在應用中按照npm的方式使用我們正在開發的庫了,我們在app.module.ts中先匯入我們的正在開發的元件,這裡可以從my-lib.module匯入全部元件,或者直接匯入我們的AlertModule(前面已經配置支援二級入口)

import { AlertModule } from 'my-lib/alert';
// import { MyLibModule } from 'my-lib';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    // MyLibModule
    AlertModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

此時在app.component.html頁面中就可以直接使用我們正在開發的alert元件了

<section>
  <dev-alert>我是一個預設型別的alert</dev-alert>
</section>

 

開啟頁面,就可以看到當前開發的效果,這時候我們就可以根據頁面表現來調整樣式和互動邏輯,此處就不繼續展示了

手把手教你搭建自己的Angular元件庫 - DevUI

編寫單元測試

前面提到我們有一個單元測試檔案,元件開發為了保證程式碼的質量和後續重構元件的穩定性,在開發元件的時候,有條件的建議加上單元測試。

由於我們調整了目錄結構,我們先修改一下相關配置

// angular.json
"my-lib": {
  ...
  "test": {
    "builder": "@angular-devkit/build-angular:karma",
    "options": {
      "main": "projects/my-lib/test.ts", // 這裡指向調整後的檔案路徑
      "tsConfig": "projects/my-lib/tsconfig.spec.json",
      "karmaConfig": "projects/my-lib/karma.conf.js"
    }
  },
}


//my-lib 目錄下的tsconfig.spec.json  


"files": [
  "test.ts" // 指向當前目錄下的測試入口檔案
]

 

下面是一個簡單的測試參考,只簡單測試了type型別是否正確,直接測試檔案中定義了要測試的元件,場景較多的時候建議提供demo,直接使用demo進行不同場景的測試。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';


import { Component } from '@angular/core';
import { AlertModule } from './alert.module';
import { AlertComponent } from './alert.component';
import { By } from '@angular/platform-browser';


@Component({
  template: `
    <dev-alert [type]="type" [showIcon]= "showIcon"[closeable]="closeable"    (closeEvent)="handleClose($event)">
    <span>我是一個Alert元件</span>
    </dev-alert>
  `
})
class TestAlertComponent {
  type = 'info';
  showIcon = false;
  closeable = false;
  clickCount = 0;
  handleClose(value) {
    this.clickCount++;
  }
}


describe('AlertComponent', () => {
  let component: TestAlertComponent;
  let fixture: ComponentFixture<TestAlertComponent>;
  let alertElement: HTMLElement;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [AlertModule],
      declarations: [ TestAlertComponent ]
    })
    .compileComponents();
  }));


  beforeEach(() => {
    fixture = TestBed.createComponent(TestAlertComponent);
    component = fixture.componentInstance;
    alertElement = fixture.debugElement.query(By.directive(AlertComponent)).nativeElement;
    fixture.detectChanges();
  });


  describe('alert instance test', () => {
    it('should create', () => {
      expect(component).toBeTruthy();
    });
  });


  describe('alert type test', () => {
    it('Alert should has info type', () => {
      expect(alertElement.querySelector('.info')).not.toBe(null);
    });


    it('Alert should has success type', () => {
      // 修改type,判斷型別改變是否正確
      component.type = 'success';
      fixture.detectChanges();
      expect(alertElement.querySelector('.success')).not.toBe(null);
    });
  }

 

通過執行 ng test my-lib就可以執行單元測試了,預設會開啟一個視窗展示我們的測試結果

到這一步,元件開發態引用、測試就完成了,功能和互動沒有問題的話,就可以準備釋出到npm了。

更多測試內容參考官方介紹:https://angular.cn/guide/testing

釋出元件

元件開發完成後,單元測試也滿足我們定義的門禁指標,就可以準備釋出到npm提供給其他同學使用了。

首先我們構建元件庫,由於ng9之後預設使用ivy引擎。官方並不建議把 Ivy 格式的庫釋出到 NPM 倉庫。因此在釋出到 NPM 之前,我們使用 --prod 標誌構建它,此標誌會使用老的編譯器和執行時,也就是檢視引擎(View Engine),以代替 Ivy。

ng build my-lib --prod

 

手把手教你搭建自己的Angular元件庫 - DevUI

構建成功後,就可以著手釋出元件庫了,這裡以釋出到npm官方倉庫為例

  1. 如果還沒有npm賬號,請到官網網站註冊一個賬號,選用public型別的免費賬號就可以
  2. 已有賬號,先確認配置的registry是否指向npm官方registry https://registry.npmjs.org/
  3. 在終端中執行npm login登入已註冊的使用者

準備工作都完成後,進入構建目錄,這裡是publish目錄,然後執行 npm publish --access public就可以釋出了,注意我們的庫名需要是在npm上沒有被佔用的,名字的修改在my-lib目錄下的package.json中修改。

手把手教你搭建自己的Angular元件庫 - DevUI

npm釋出參考: https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry

 

如果是內部私有庫,按照私有庫的要求配置registry就可以了,釋出命令都是一樣的。

 

加入我們

 

我們是DevUI團隊,歡迎來這裡和我們一起打造優雅高效的人機設計/研發體系。招聘郵箱:muyang2@huawei.com。

文/DevUI June

 



相關文章