如何修复ngx-bootstrap出现的“can't resolve”编译报错问题
问题根因
报错是由于ngx-bootstrap依赖的两个Angular官方模块未在你的项目中安装和注册导致:@angular/animations 负责动画相关能力,@angular/forms 负责表单相关能力。
解决方案按如下步骤执行即可:
- 安装缺失的依赖包
根据你使用的包管理器执行对应命令:
- npm用户执行:
npm install @angular/animations @angular/forms - yarn用户执行:
yarn add @angular/animations @angular/forms - pnpm用户执行:
pnpm add @angular/animations @angular/forms
- 在根模块中注册依赖模块
打开项目下的src/app/app.module.ts文件,添加如下内容:
// 新增导入 import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; // 推荐按需导入ngx-bootstrap的模态模块,避免全量导入 import { ModalModule } from 'ngx-bootstrap/modal'; @NgModule({ imports: [ // 原有其他导入保留,新增以下三个模块 BrowserAnimationsModule, FormsModule, ModalModule.forRoot() ] }) export class AppModule { }
- 修正导入语句
把你原来的全量导入语句:
import { BsModalRef } from 'ngx-bootstrap';
修改为按需导入路径,避免全量加载ngx-bootstrap所有组件的依赖:
import { BsModalRef } from 'ngx-bootstrap/modal';
- 重启开发服务
停掉当前正在运行的ng serve进程,重新执行ng serve启动项目即可,报错会完全消除。
补充注意:如果执行完以上操作仍有报错,请检查ngx-bootstrap版本和你的Angular核心版本是否匹配,大版本号需要对应(比如Angular 16对应ngx-bootstrap 11.x版本)
内容的提问来源于stack exchange,提问作者Funn_Bobby
相关产品推荐
相关产品推荐

