iT邦幫忙

0

Angular Library 建立與設定

  • 分享至 

  • xImage
  •  

建立angular library

1.建立空專案

ng new app-test-lib --create-application=false --routing false --style css
  • 目錄結構
    app-test-web
    ----node_modules
    ----projects

2.於 projects 下建立library
ng g library app-lib

@Component({
  selector: 'lib-app-lib',
  template: `
    <p>
      app-lib works!  OK
    </p>
  `,
  styles: []
})
export class AppLibComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

  • 目錄結構
    app-test-web
    ----node_modules
    ----projects
    --------app-lib

3.於 projects 下建立測試 library 的專案
ng g application app-test

app-test-web
----node_modules
----projects
--------app-lib
--------app-test

4.於app-test-web 先 ng build 產生dist
C:\app-test-lib> ng build

5.設定path
(1)於app-test-web 下的 tsconfig.json

增加 "projects/app-lib/src/public-api.ts"

"paths": {
  "app-lib": [
    "dist/app-lib",
    "projects/app-lib/src/public-api.ts"
  ]
}

(2)src/public-api.ts是設定 library 要 export 的項目

export * from './lib/app-lib.service';
export * from './lib/app-lib.component';
export * from './lib/app-lib.module';

6.於 app-test 使用 app-lib
於 app.module.ts import AppLibModule,
藉由 "projects/app-lib/src/public-api.ts" 導向到build完的app-lib

import { AppLibModule } from 'app-lib';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AppLibModule
  ],

7.於app-test測試app-lib專案
(1)將app-test ng serve
C:\app-test-lib> ng serve app-test

(2) build app-lib library專案 並 -- watch
C:\app-test-lib> ng build app-lib --watch

這樣 app-lib 只要有更改,可以直接在 app-test 看到結果

**8.於 app.component.html 加上 **
<lib-app-lib></lib-app-lib>

確認結果。

參考連結:
Angular.io :
https://angular.io/guide/creating-libraries
保哥:
https://blog.miniasp.com/post/2019/04/19/Learn-Angular-Library-and-build-custom-Form-Validators


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言