使用ng-packagr打包Angular 5库后在应用中运行出现TypeError问题求助
ng serve出现Cannot read property 'members' of undefined的问题 我之前在维护Angular 5项目时也碰到过一模一样的错误,结合你的配置细节,给你几个针对性的解决方案,一步步排查应该能解决问题:
1. 修正库的package.json入口配置
你当前库的package.json里main和typings指向的是源文件ocinfra/index.ts,这是核心错误——ng-packagr打包后会生成编译好的UMD包和类型声明文件,必须把入口改成打包后的产物:
{ "main": "bundles/oc-infra.umd.js", "typings": "ocinfra/index.d.ts" }
直接指向源文件会导致应用编译时跳过ng-packagr的打包逻辑,引发类型解析异常。
2. 升级ng-packagr到适配Angular 5的稳定版本
你用的ng-packagr@1.6.0存在不少已知的兼容性bug,建议升级到专门适配Angular 5的1.7.0版本:
npm install ng-packagr@1.7.0 --save-dev
升级完成后重新执行npm run packagr打包你的库。
3. 对齐库与应用的Angular核心依赖版本
你的库用的是Angular 5.1.0,而应用是5.2.1,虽然同属Angular 5分支,但小版本差异可能触发类型不兼容问题。请把库的package.json里的Angular核心依赖统一升级到5.2.1:
{ "@angular/animations": "^5.2.1", "@angular/cdk": "^5.2.5", "@angular/common": "^5.2.1", "@angular/compiler": "^5.2.1", "@angular/core": "^5.2.1", "@angular/forms": "^5.2.1", "@angular/http": "^5.2.1", "@angular/material": "^5.2.5", "@angular/platform-browser": "^5.2.1", "@angular/platform-browser-dynamic": "^5.2.1", "@angular/router": "^5.2.1" }
执行npm install更新依赖后重新打包库。
4. 用标准流程部署库到应用
不要手动复制打包文件到应用的node_modules,正确流程是:
- 在库目录执行
npm pack生成.tgz格式的本地包 - 在应用目录执行
npm install /path/to/your-library.tgz安装本地包
这样能确保所有打包生成的关键文件(类型声明、UMD包、元数据文件)都被完整安装。
5. 清理缓存并重新构建
缓存经常会导致这类诡异的编译错误,执行以下步骤彻底清理:
- 清理应用的依赖和npm缓存:
rm -rf node_modules package-lock.json npm cache clean --force npm install
- 清理Angular CLI的本地缓存:
rm -rf dist .angular-cli.cache
之后重新运行ng serve尝试启动应用。
6. 检查库的tsconfig.json配置
确保库的编译配置符合Angular库的要求,关键配置如下:
{ "compilerOptions": { "target": "es5", "module": "es2015", "lib": ["es2015", "dom"], "declaration": true, "strict": true, "skipLibCheck": true, "moduleResolution": "node", "experimentalDecorators": true, "emitDecoratorMetadata": true }, "angularCompilerOptions": { "skipTemplateCodegen": true, "strictMetadataEmit": true } }
其中strictMetadataEmit能确保生成的元数据文件没有语法错误,避免应用编译时解析元数据出错。
如果以上步骤都尝试后仍有问题,可以检查库中是否存在循环依赖或者组件/服务的类型声明错误,这类问题也可能触发members undefined的异常。
内容的提问来源于stack exchange,提问作者Guillermo Vigil Rodríguez

