Angular 如果我在编译器选项中有类型 "node",则 ng 测试会导致错误

Angular ng test cause error if I have types "node" in compiler option

环境

对于 angular 应用程序,如果我在 tsconfig.json 的编译器选项中添加类型,ng test 会失败。

错误如

Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
S2304: Cannot find name 'expect'

我的tsconfig如下。

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true,
    "types": ["node"],  // <= this part
  }
}

我知道如果我删除那个 types,它就会起作用。但实际上因为我使用的包,我需要它。

我希望有人知道这种行为。

在官方 google 文档中,angularCompilerOptions 属性 中没有类型选项: 可用选项的详尽列表:

  1. allowEmptyCodegenFiles
  2. 注释为
  3. annotateForClosureCompiler
  4. 禁用ExpressionLowering
  5. 禁用TypeScriptVersionCheck
  6. 启用常春藤
  7. enableResourceInlining
  8. 启用旧版模板
  9. flatModuleId
  10. flatModuleOutFile
  11. fullTemplateTypeCheck
  12. generateCodeForLibraries
  13. 保留空白
  14. skipMetadataEmit
  15. skipTemplateCodegen
  16. strictMetadataEmit
  17. strictInjectionParameters
  18. strictTemplates
  19. 追踪

如果你需要节点类型,你可以使用 npm i @types/node 来安装它们,类型被添加到这个层次结构下:

{
   "compilerOptions": {
       "types" : ["node", "lodash", "express"]
   }
}
 

自己回答

tsconfig.json 中删除类型并将其添加到 tsconfig.app.json

tsconfig.json

   // "types": ["node"], // remove

tsconfig.app.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"] // <= add
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}