天天看點

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

執行指令行: ng run storefrontapp:server:production

報錯:

Error: projects/storefrontapp/src/app/app.module.ts:33:30 - error TS2307: Cannot find module ‘feature-libs/my-lib/src/public-api’ or its corresponding type declarations.

33 import { MyLibService } from ‘feature-libs/my-lib/src/public-api’;

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

我們執行完 npm build test-lib 之後,dist 檔案夾裡生成對應的資源檔案:

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

然後我們按住 ctrl 之後再單擊,就能看到 test-lib 位于 dist 檔案夾中的準确實作位置:

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

同理,我們也能按照 Spartacus 其他的 feature library 設計一樣,将 test-lib 的 paths 值,指定成feature-libs 内的資源檔案,而非 dist 檔案夾。

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

如果要讓應用在伺服器端渲染即 Server Side Rendering 模式下工作,需要将 library 位址添加到 tsconfig.server.json 中:

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

CSR:ng build storefrontapp

Server Side Rendering : ng run storefrontapp:server

成功建構:

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

Angular independent feature sub libraries

不知道大家是否注意到了,Angular (@angular) 以某種方式分成不同的“部分”,例如:

@angular/common

@angular/core

@angular/forms

等等。

而 每一個部分,例如 @angular/common 又有不同的子目錄可供導入:

@angular/common/http

@angular/common/locale

@angular/common/testing

Angular 支援多個開箱即用的子庫。

預設的項目結構包含一個“app”應用程式,它是一個正常的 Angular 項目,然後你添加額外的子庫,即 Angular 庫項目。有放置在庫子檔案夾中。

一個 Angular 項目可以包含多個子庫項目。

每個子庫項目都可以作為單獨的 npm 包釋出,因為它們有自己的 package.json 檔案。

npm 支援稱為作用域包名稱的東西。這允許您将包命名為 @angular/core,其中 @angular 是包的範圍。

您可以像這樣将作用域庫添加到目前的 Angular 項目中。

ng generate library @my-scope/my-library

從範圍項目導入時,它必須以 scope 為字首。

例如;

Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義
Angular tsconfig.json 檔案裡的 paths 用法和 scoped module 定義

繼續閱讀