【问题标题】:Why isn't VS Code respecting TypeScript paths?为什么 VS Code 不尊重 TypeScript 路径?
【发布时间】:2021-11-17 05:07:15
【问题描述】:

在我通过 ts-node 和 jasmine 运行测试的 TypeScript 项目中,我在 tsconfig.json 中定义了一些路径

{
  "compilerOptions": {
      "baseUrl": "src",
      "target": "es5",
      "module": "commonjs",
      "lib": [
          "es5",
          "es2015",
          "DOM"
      ],
      "moduleResolution": "Node",
      "outDir": "./dist/cjs",
      "declaration": true,
      "sourceMap": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "noImplicitAny": false,
      "removeComments": true,
      "strict": true,
      "paths": {
            "@common": ["common/index"],
            "@crashes": ["crashes/index"]
      }
  },
  "files": [
      "./src/index.ts"
  ]
}

我可以在我的生产代码中通过路径 @common@crashes 导入,但由于某种原因,VS Code 在我的 spec.ts 文件中给了我错误 Cannot find module '@common' or its corresponding type declarations.

如何让 VS Code 在我的测试中识别 TypeScript 路径?

【问题讨论】:

    标签: node.js typescript jasmine tsconfig ts-node


    【解决方案1】:

    这是因为 VS Code 的智能感知将遵循 tsconfig.json 中的规则。在这种情况下,我没有在 TypeScript 编译中包含 spec.ts 文件。此外,我不想在项目的构建输出中包含 TypeScript 文件。

    解决方法如下:

    1. tsconfig.json 中删除files 属性
    2. 引入扩展 tsconfig.json 的新 tsconfig.dist.json 并在此处添加 files 属性
    {
        "extends": "./tsconfig.json",
        "compilerOptions": {
            "target": "es5",
            "module": "commonjs",
            "outDir": "./dist/cjs",
        },
        "files": [
            "./src/index.ts"
        ]
      }
    
    1. 在发布脚本中使用新的tsconfig.dist.json

    此外,当我完成所有这些操作后,当我尝试使用 ts-node 运行 jasmine 测试时出现以下错误:

    > ts-node node_modules/jasmine/bin/jasmine --config=spec/support/jasmine.spec.json
    
    Error: Cannot find module '@common'
    

    解决此错误的方法是安装tsconfig-paths 并在package.json 中更新我的test 脚本

    {
       "scripts": {
            "test": "ts-node -r tsconfig-paths/register node_modules/jasmine/bin/jasmine --config=spec/support/jasmine.spec.json"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2021-10-20
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多