zl程序教程

您现在的位置是:首页 >  前端

当前栏目

关于 Angular 项目类型为 library 的工程使用 tsconfig.json 的问题

Angular项目JSONJSON 类型 关于 工程 library
2023-09-14 09:02:52 时间

我今天做 Angular 开发时,遇到一个很奇怪的问题:

在某个 Angular library 项目里,无法正确解析出 @Spartacus/core,

错误消息:

Cannot find module ‘@spartacus/core’ or its corresponding type declarations.ts(2307)

但是,就在同一工程的单元测试 .spec.ts 文件里,库的解析是正确的。这种在同一文件夹里不同文件对另外同一个库的解析,出现如此不一致的现象,让我非常费解。

后来经过一番分析,发现是库文件夹里文件 tsconfig.json 引起的原因。

我把该文件的内容清空只剩下面一行,问题消失。

最后问题定位到,加了下图这三行进行 paths 设置后,就出问题了:

 "paths": {
      "@spartacus/core": ["dist/core"],
      "@spartacus/storefront": ["dist/storefrontlib"],
      "@spartacus/cart": ["dist/cart"]
    },

每次 Visual Studio Code 里修改了 tsconfig.json 之后,都会显示 Initializing Angular Language features:

目录中存在 tsconfig.json 文件表明该目录是 TypeScript 项目的根目录。 tsconfig.json 文件指定了编译项目所需的根文件和编译器选项。

https://stackoverflow.com/questions/52147201/angular-6-declare-path-for-library-in-tsconfig-lib-json

Angular will use the tsconfig.json file, which is configured in the angular.json file in architect --> build --> options --> tsconfig. Whereas VS Code uses the tsconfig.json file, which is at the bottom of the workspace. You need to add the paths in both configurations to get both of them to work correctly, or change the project to use the base tsconfig.json file in the angular.json file.

The tsconfig.json file has a property that extends which will take another file as base and override everything which are declared in the tsconfig.lib.json file. So if you have paths declared in the tsconfig.lib.json file, then the paths are no longer needed in the tsconfig.json file.

2022-7-11 更新

Visual Studio Code 有时候找不到 @Spartacus/core 或者 @Spartacus/storefront

Cannot find module ‘@spartacus/core’ or its corresponding type declarations.ts(2307)


但是在单元测试代码里,一切正常:

tsconfig.json 的文件修改:

创建了自己的 tsconfig.json 来扩展 root:

答案:

检查了其他的 SAP Spartacus libraries, 这些库用的都是 tsconfig.lib.json, 而不是 tsconfig.json.