Angular自定义模块更新不生效问题求助
问题描述
我维护了一个包含多个自定义模块的Angular类库,近期更新模块时遇到异常:
- 为修复模块调用问题,给
transferRadius函数添加了空数组检查:
private transferRadius(buttons: HTMLButtonElement[], alignment: string): void { if(buttons.length === 0) { return; } if (alignment === 'vertical') { this.buttonGroup.nativeElement.style.borderTopLeftRadius = this.getButtonRadius(buttons[0], 'top-left'); this.buttonGroup.nativeElement.style.borderTopRightRadius = this.getButtonRadius(buttons[0], 'top-right'); this.buttonGroup.nativeElement.style.borderBottomRightRadius = this.getButtonRadius(buttons[buttons.length - 1], 'bottom-right'); this.buttonGroup.nativeElement.style.borderBottomLeftRadius = this.getButtonRadius(buttons[buttons.length - 1], 'bottom-left'); } else { this.buttonGroup.nativeElement.style.borderTopLeftRadius = this.getButtonRadius(buttons[0], 'top-left'); this.buttonGroup.nativeElement.style.borderTopRightRadius = this.getButtonRadius(buttons[buttons.length - 1], 'top-right'); this.buttonGroup.nativeElement.style.borderBottomRightRadius = this.getButtonRadius(buttons[buttons.length - 1], 'bottom-right'); this.buttonGroup.nativeElement.style.borderBottomLeftRadius = this.getButtonRadius(buttons[0], 'bottom-left'); } }
- 更新后将类库安装到项目中,
node_modules里的模块.mjs文件能看到新增的检查代码,但运行ng build或ng serve后,浏览器中代码依旧缺失空数组检查,原异常未修复。 - 已排除浏览器缓存问题(用
ctrl + f5刷新、清除缓存、换Firefox测试均无效)。 - 另一模块的
selector修改也未生效:代码中设置selector: 'mat-editor[content]',,但构建后显示为args: [{ selector: 'lib-mat-editor', template: "<div class=\"mat-editor\"></div>" }],导致<mat-editor>元素没有预期的<div>子元素。 - 项目
dist文件夹中模块文件已合并到main...js等文件中,未找到单独的模块文件。
解决方案
重新构建并更新类库依赖
自定义类库修改后,必须先在类库目录执行构建命令(如ng build your-library-name),确保修改被编译到构建产物中。如果是本地安装的类库,需在项目目录重新执行npm install ../path-to-your-library;如果是发布到npm的类库,要更新版本号后重新发布,再在项目中执行npm update your-library-name。清除Angular CLI构建缓存
Angular CLI会缓存构建产物,可通过以下方式清空:- 执行
ng serve --no-cache或ng build --no-cache,禁用缓存启动/构建; - 删除项目根目录下的
.angular/cache文件夹; - 执行
ng build --delete-output-path,确保dist文件夹被完全清空后重新构建。
- 执行
检查类库的package.json配置
确认类库package.json中的main、module、exports字段指向最新的构建产物路径,避免项目引用未编译的源码或旧的构建文件。例如:{ "main": "./dist/your-library/bundles/your-library.umd.js", "module": "./dist/your-library/fesm2020/your-library.mjs", "exports": { ".": { "types": "./dist/your-library/your-library.d.ts", "esm2020": "./dist/your-library/fesm2020/your-library.mjs", "umd": "./dist/your-library/bundles/your-library.umd.js" } } }验证类库构建产物的正确性
查看类库dist文件夹中的组件元数据文件,确认selector等修改已被正确编译。比如检查组件对应的.js或.mjs文件,确保selector值为mat-editor[content]而非旧值。检查项目的Angular构建优化配置
打开项目angular.json,查看build配置中的optimization、vendorChunk等选项。如果开启了vendorChunk,可尝试临时关闭(设置为false),重新构建后查看是否生效,再逐步排查缓存问题。
内容的提问来源于stack exchange,提问作者Otto Abnormalverbraucher
相关产品推荐
相关产品推荐

