Angular 5 NPM包构建失败:TypeScript编译文件缺失问题求助
解决Angular 5 NPM模块安装后的TypeScript编译错误
我之前也碰到过一模一样的问题,结合你参考的这类Angular库结构,给你几个针对性的解决步骤,应该能搞定这个报错:
1. 先检查你的ngx-chat包本身的TypeScript配置
这个错误大概率是你的包没有正确编译,或者打包时没配置好入口文件导致的:
- 打开包项目里的
tsconfig.json,确认compilerOptions里的outDir指向./dist(或者你指定的编译输出目录),同时include要覆盖所有源文件:
{ "compilerOptions": { "outDir": "./dist", "target": "es5", "module": "es2015", "moduleResolution": "node", "declaration": true, "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2017", "dom"] }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
- 然后在包的
package.json里,把main、module、typings这几个字段都指向编译后的dist目录里的文件,别指向源文件:
{ "name": "ngx-chat", "version": "0.0.1", "main": "./dist/bundles/ngx-chat.umd.js", "module": "./dist/esm5/ngx-chat.js", "typings": "./dist/esm5/ngx-chat.d.ts", // 其他依赖、脚本字段... }
- 别忘了在包项目里执行编译命令,比如用Angular CLI的
ng build --prod(如果是用CLI创建的库),确保dist目录生成后再发布或者本地安装。
2. 调整使用包的Angular项目的tsconfig
如果包本身编译没问题,但项目还是报错,那得让你的项目识别包的TypeScript文件:
- 打开项目根目录的
tsconfig.json,在include数组里加上你的包路径:
{ "include": [ "src/**/*", "node_modules/ngx-chat/**/*" ] }
不过更推荐的是把包本身的编译配置弄对,毕竟让项目去编译node_modules里的文件既慢又容易出其他问题。
3. 确认包的入口文件index.ts配置正确
你的包根目录的index.ts要正确导出模块,比如:
export * from './src/ngx-chat.module';
并且编译后的dist目录里要有对应的导出文件,这样项目才能正确找到模块。
4. 本地安装的小细节
如果你是本地通过npm install ../ngx-chat这种方式安装的,一定要确保包项目已经编译生成了dist目录,不然安装的其实是源文件,自然会触发编译错误。
额外提一句:Angular 5之后官方支持了库模式(
ng generate library),用这个方式创建的库会自动帮你配置好编译、打包的所有细节,比自己手动搭结构省心多了,你可以试试这个方法重构你的ngx-chat包,能避免很多踩坑的地方。
内容的提问来源于stack exchange,提问作者Aleksandr Gorin
相关产品推荐
相关产品推荐

