Angular 10升级问题:找不到'@ng-bootstrap/ng-bootstrap/util/positioning'模块
问题详情
将Angular 8应用升级到Angular 10后,执行构建时出现如下错误:
ERROR in ./src/app/components/input/typeahead.ts Module not found: Error: Can't resolve 'node_modules/@ng-bootstrap/ng-bootstrap/util/positioning'
当前环境:
- Angular版本:10
- ng-bootstrap版本:7.x
原因分析
ng-bootstrap 7.x(适配Angular 10)对内部模块结构进行了重构,原内部路径util/positioning已不再对外暴露;同时代码中直接写死node_modules前缀的导入方式本身不符合Node模块解析规范,属于错误用法。
解决方案
1. 修正导入路径的错误写法
首先移除导入路径中的node_modules前缀,Node会自动从项目依赖中查找模块,正确的基础路径应为@ng-bootstrap/ng-bootstrap。
将原导入代码:
import { ... } from 'node_modules/@ng-bootstrap/ng-bootstrap/util/positioning';
修改为:
import { ... } from '@ng-bootstrap/ng-bootstrap/util/positioning';
2. 适配ng-bootstrap 7.x的模块结构
如果修正路径后仍报错,说明该模块在7.x中已迁移位置。ng-bootstrap 7.x将定位相关工具类移至positioning独立模块,可改为以下导入方式:
import { Positioning } from '@ng-bootstrap/ng-bootstrap/positioning';
若你是在自定义typeahead组件中使用该工具,也可检查ng-bootstrap官方Typeahead组件的公共API,确认是否已无需手动导入内部定位工具。
3. 清理依赖缓存并重新构建
执行以下命令彻底清理依赖缓存,避免残留的旧依赖文件干扰:
rm -rf node_modules package-lock.json npm install npm run build -- --clean
4. 避免导入ng-bootstrap内部私有模块
ng-bootstrap的util等内部模块属于私有实现,版本升级时可能随时被修改或移除。后续开发应优先使用其对外暴露的公共API,避免直接依赖内部路径。
内容的提问来源于stack exchange,提问作者Chavan Vishal

