前言
為了在我的編輯器中使用 Angular,我用 Angular 編寫了一個(gè)重命名功能。而為了使用它,我得再次使用一次 customEvent ,而在這個(gè)微前端架構(gòu)的系統(tǒng)中,其事件通訊機(jī)制已經(jīng)相當(dāng)?shù)膹?fù)雜。在這部分的代碼進(jìn)一步惡化之前,我得嘗試有沒有別的方式。于是,我想到了之前在其它組件中使用的 Web Components 技術(shù),而 Angular 6 正好可以支持。
下面話不多說了,來一起看看詳細(xì)的介紹吧
HTML 中引入 Web Components
我所需要做的事情也相當(dāng)?shù)暮?jiǎn)單,只需要將我的組件注冊(cè)為一個(gè) customElements,稍微改一下 app.module.ts 文件。在這種情況之下,我們就可以構(gòu)建出獨(dú)立于框架的組件。
如下是原始的 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 中傳遞參數(shù): <interact-bar filename="phodal.md"></interact-bar> ,或者監(jiān)聽對(duì)應(yīng)的 @Output 事件:
const bar = document.querySelector('interact-bar');bar.addEventListener('action', (event: any) => { ...})事實(shí)證明,使用 Angular 構(gòu)建的 Web Components 組件是可以用的。于是,我便想,不如在 React 中引入 Angular 組件吧。
React 中引入 Angular 組件
于是,便使用 create-react-app 創(chuàng)建了一個(gè) DEMO,然后引入組件:
<div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </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 參數(shù)可以成功地傳遞到 Angular 代碼中,而 action 在當(dāng)前似乎還不行。但是毫無疑問,它在未來是可用的。
Demo 見: https://phodal.github.io/wc-angular-demo/
Repo 見: https://github.com/phodal/wc-angular-demo
這個(gè)時(shí)候,我遇到了一個(gè)問題,我使用 Angular 構(gòu)建的這個(gè)組件,大概是有 257kb。這個(gè)大小的組件,但是有點(diǎn)恐怖。
Web Components 框架構(gòu)建組件
在那些微前端相關(guān)的文章中,我們指出類似于 Stencil 的形式,將組件直接構(gòu)建成 Web Components 形式的組件,隨后在對(duì)應(yīng)的諸如,如 React 或者 Angular 中直接引用。
新聞熱點(diǎn)
疑難解答
圖片精選