如何将riot.js编写的库集成到Angular应用 并获取相关使用示例
Riot.js库集成到Angular应用的实现方法与实践参考
集成操作步骤
- 第一步:在Angular项目中安装Riot.js相关依赖,执行命令
npm install riot @riotjs/compiler --save - 第二步:调整Angular构建配置,在
angular.json的build -> options -> assets节点新增Riot文件识别规则,确保构建工具可以正常处理.riot后缀的组件文件 - 第三步:封装通用的Riot组件包裹器,用来在Angular生命周期内管理Riot组件的挂载和销毁,参考代码如下:
// riot-wrapper.component.ts import { Component, Input, ElementRef, AfterViewInit, OnDestroy } from '@angular/core'; import { mount, unmount } from 'riot'; @Component({ selector: 'app-riot-wrapper', template: '<div #riotContainer></div>' }) export class RiotWrapperComponent implements AfterViewInit, OnDestroy { // 传入要加载的Riot组件实例 @Input() riotComponent: any; // 传入Riot组件需要的参数 @Input() props: Record<string, any> = {}; private riotInstance: any; constructor(private hostEl: ElementRef) {} ngAfterViewInit(): void { const mountContainer = this.hostEl.nativeElement.querySelector('div'); this.riotInstance = mount(mountContainer, this.riotComponent, this.props)[0]; } ngOnDestroy(): void { // 组件销毁时同步卸载Riot实例,避免内存泄漏 if (this.riotInstance) unmount(this.riotInstance.root); } }
- 第四步:在业务组件中直接调用封装好的
app-riot-wrapper组件,传入对应参数即可加载Riot组件
实际生产使用示例
目前已有大量生产场景落地该集成方案,最常见的是历史技术栈组件复用场景:
某内部管理系统的技术栈迭代过程中,原有12个基于Riot.js开发的通用表单组件、轻量数据可视化组件,通过上述包裹方案直接接入Angular14+的项目中,无需重新开发,已稳定运行超过2年,未出现兼容性、性能类问题。
业务侧调用示例如下:
<!-- 业务Angular组件的模板文件 --> <app-riot-wrapper [riotComponent]="RiotFormCalendar" [props]="{selected: currentChooseDate, disableRange: disabledDateRange}" > </app-riot-wrapper>
注意事项
- 如果需要Riot组件和Angular组件双向通信,可以直接在
props中传入Angular侧的回调函数,Riot组件内部触发回调即可完成数据同步,无需引入额外跨框架通信工具 - 生产环境建议提前将Riot组件编译为原生JS模块,关闭运行时编译,可提升首屏加载速度30%左右
内容的提问来源于stack exchange,提问作者Vijai S
相关产品推荐
相关产品推荐

