网站搜索

angular - Visual Studio Code 无法解析 spec 文件的绝对导入


小提示:如果这个问题应该被删除,或者应该发布到 Visual Studio Code 的错误反馈表单,请告知我,我会照做。

问题

在使用 Angular 工作区时,Visual Studio Code 无法解析 spec 文件中的绝对或基于路径的导入。这些导入在非 spec 文件中完全按预期工作,spec 文件中的相对导入同样有效。我之所以确信这是一个 Visual Studio Code 特定的问题的真正原因是,通过命令行运行 Angular 测试仍然可以成功完成。每个测试都能顺利运行。此外,我能够在 IntelliJ(Goland)中使用带有 Angular 插件的环境,并且在该编辑器中,spec 文件在导入方面的行为是正常的。

背景

我按照这个教程创建了一个包含一个库和两个使用应用的 Angular 工作区。我在根目录配置了一个基础 tsconfig.json 文件,此外在每个项目中都有一个 tsconfig.json 和 tsconfig.spec.json,并且每个文件都在 angular.json 中被引用。我同样确信这些文件的格式都是正确的,因为测试/构建依然可以正常工作。如果有关系的话,目前使用的测试配置是 Karma + Jasmine。

尝试解决

有大量帖子,比如 Visual Studio Code 不识别 Typescript 中的绝对导入,这表明 tsconfig 配置错误,而尝试每一个可能的修复可能会让人望而生畏。可以这么说,我尝试了很多提议的解决方案,但没有一个对我有效。

这些文件

这是其中一个项目的 tsconfig 文件。

tsconfig.json
{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/app",
    "baseUrl": "./", <---- These imports work in non-spec files 
    "paths": { <---- These imports work in non-spec files
      "myLibrary": [
        "./../../dist/my-library/my-library",
        "./../../dist/my-library"
      ]
    },
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}
tsconfig.spec.json
{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/spec",
    "types": [
      "jasmine", "node"
    ],
    "baseUrl": "./", <---- These imports don't work in spec files
    "paths": { <---- These imports don't work in spec files
      "myLibrary": [
        "./../../dist/my-library/my-library",
        "./../../dist/my-library"
      ]
    },
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

根目录级别的 tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    /* many different options, but the paths and baseUrl options are not set */
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

一些其他提示

除了相对导入和基于路径的导入无法使用之外,Jasmine 提供的 describe/beforeEach/it/expect 函数也无法被检测到。在 IntelliJ 中,这些会解析到 node_modules/@types/jasime/index.d.ts,但在 Visual Studio Code 中会提示错误 Cannot find name 'describe'. Do you need to install type definitions for a test runner? ts(2582)。不过我对这个提示持保留态度,因为有时这些函数会正常解析,我不确定为什么会不一致。如前所述,相对导入是可以使用的,我知道 baseUrl 属性控制绝对导入的方式,但我不确定 Visual Studio Code 如何处理相对导入。无论如何,它可以成功处理。

总的来说,我希望能找到一些解决方案,让我能够继续使用 VS Code,因为我喜欢这个编辑器。然而,编写测试是项目的重要部分,如果导入不起作用,那么这个编辑器就无法使用。