前言
為了在我的編輯器中使用 Angular,我用 Angular 編寫了一個重命名功能。而為了使用它,我得再次使用一次 customEvent ,而在這個微前端架構的系統中,其事件通訊機制已經相當的復雜。在這部分的代碼進一步惡化之前,我得嘗試有沒有別的方式。于是,我想到了之前在其它組件中使用的 Web Components 技術,而 Angular 6 正好可以支持。
下面話不多說了,來一起看看詳細的介紹吧
HTML 中引入 Web Components
我所需要做的事情也相當的簡單,只需要將我的組件注冊為一個 customElements,稍微改一下 app.module.ts 文件。在這種情況之下,我們就可以構建出獨立于框架的組件。
如下是原始的 module 文件:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule { }
如下則是新的 module 文件:
@NgModule({
declarations: [InteractBar],
imports: [BrowserModule],
entryComponents: [InteractBar]
})
export class AppModule {
constructor(private injector: Injector) {
const interactBar = createCustomElement(InteractBar, {injector});
customElements.define('interact-bar', interactBar);
}
}
然后,只需要就可以在 HTML 中傳遞參數: <interact-bar filename="phodal.md"></interact-bar> ,或者監聽對應的 @Output 事件:
const bar = document.querySelector('interact-bar');
bar.addEventListener('action', (event: any) => {
...
})
事實證明,使用 Angular 構建的 Web Components 組件是可以用的。于是,我便想,不如在 React 中引入 Angular 組件吧。
React 中引入 Angular 組件
于是,便使用 create-react-app 創建了一個 DEMO,然后引入組件:
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2 className="App-title">Welcome to React</h2>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<interact-bar filename="phodal.com" onAction={this.action}></interact-bar>
</p>
</div>
嗯,it works。至少 filename 參數可以成功地傳遞到 Angular 代碼中,而 action 在當前似乎還不行。但是毫無疑問,它在未來是可用的。
Demo 見: https://phodal.github.io/wc-angular-demo/
Repo 見: https://github.com/phodal/wc-angular-demo
這個時候,我遇到了一個問題,我使用 Angular 構建的這個組件,大概是有 257kb。這個大小的組件,但是有點恐怖。
Web Components 框架構建組件
在那些微前端相關的文章中,我們指出類似于 Stencil 的形式,將組件直接構建成 Web Components 形式的組件,隨后在對應的諸如,如 React 或者 Angular 中直接引用。
如下是一個使用 Stencil 寫的 Web Components 的例子:
@Component({
tag: 'phodit-header',
styleUrl: 'phodit-header.css'
})
export class PhoditHeader {
@State() showCloseHeader = false;
componentDidLoad() {...}
handleClick() {...}
render() {
if (this.showCloseHeader) {...}
return (<div></div>);
}
}
使用它構建出來的組件,大概可以在 30kb 左右的大小。
不論是不是一個經量級的方案,但是它至少證明了組件復用的可行性。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。