Angular 9集成Typeform Embed报错:无法解析react及react-dom依赖
解决Angular 9集成Typeform Embed时的React依赖错误
嘿,我来帮你搞定这个问题!你遇到的报错是因为你安装的@typeform/embed包本质上是为React项目设计的,它依赖React和ReactDOM这两个库,而你的Angular项目里并没有安装它们,所以才会触发这些"Module not found"的错误。
给你两个可行的解决方案,推荐用第一种,更适配Angular项目:
方案1:使用纯JavaScript嵌入(推荐)
这种方式不需要依赖React,直接用Typeform提供的官方纯JS脚本,步骤如下:
- 在项目的
src/index.html中添加Typeform的嵌入脚本:
<script src="https://embed.typeform.com/embed.js"></script>
- 在你的组件类(
component.ts)中,通过全局window对象调用Typeform的嵌入方法,记得在DOM渲染完成后初始化(比如用ngAfterViewInit钩子):
import { Component, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements AfterViewInit { ngAfterViewInit(): void { this.initTypeform(); } initTypeform(): void { // 先找到要嵌入Typeform的DOM容器 const container = document.getElementById('typeform-container'); if (container) { // 替换成你的Typeform ID和自定义配置 window.typeformEmbed.makeWidget(container, 'YOUR_TYPEFORM_ID', { hideHeaders: true, hideFooters: true, width: '100%', height: '600px' }); } } }
- 在组件模板(
component.html)中添加一个容器元素:
<div id="typeform-container"></div>
方案2:安装React依赖(不推荐)
如果你一定要使用npm包的方式,那就需要安装React和ReactDOM作为项目依赖,但这会在Angular项目中引入不必要的React框架,增加项目复杂度和体积:
npm install react react-dom --save
安装完成后,你之前的代码应该就能正常运行了,但还是建议用方案1,更符合Angular项目的技术栈。
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

