分享

解决 Angular 官网下载的库 Schematics 执行 npm run build 时遇到的编译错误

 汪子熙 2021-10-18

我在 Angular 官网下载的 library Schematics 例子,运行命令行 npm run build 时,遇到如下错误:

npm run build
my-lib@0.0.1 build c:\Code\SPA\schematics-for-libraries\projects\my-lib tsc -p tsconfig.schematics.json

schematics/my-service/index.ts:39:7 - error TS2322: Type 'string | number | boolean | JsonArray | JsonObject | null | undefined' is not assignable to type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'.

39 options.project = workspace.extensions.defaultProject; ~~~~~~~~~~~~~~~

schematics/my-service/index.ts:42:44 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

解决方法

这个 project 的数据类型是我们自己在 schema.ts 里定义的,故调整成和 workspace.extensions.defaultProject 一致即可。

修改之前:

修改之后,又遇到了新问题:Cannot find name 'JsonArray'

其实直接在原始代码位置加上 as string 即可,意思是告诉编译器,程序员非常清楚,在这个上下文里,workspace.extensions.defaultProject 的类型,一定是 string.

修复之后遇到另一个错误:

'options' is declared but its value is never read.ts(6133)

这个错误的解决方案比较简单:

参数名前加上一个下划线即可。

最后,npm run build 成功执行:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多