Blog

Blog

PHODAL

React 中引入 Angular 组件

为了在我的编辑器中使用 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" />
    <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 参数可以成功地传递到 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 左右的大小。

不论是不是一个经量级的方案,但是它至少证明了组件复用的可行性。

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签