【问题标题】:TypeScript path aliases stopped working with project referencesTypeScript 路径别名停止使用项目引用
【发布时间】:2021-04-20 21:33:16
【问题描述】:

以前,我遇到了一个关于package.json 不在rootDir 之下的问题,但是在按照this answer 建议的步骤之后,我可以找到一个question on StackOverflow 来解决完全相同的问题,我最终得到了尝试通过运行 tsc --build src 生成声明文件时,我的路径别名无法被 tsc 识别

注意:我没有在tsconfig.json 上包含声明相关的属性,比如"declaration": true"emitDeclarationOnly": true,因为一开始我什至无法转换代码,我专注于让路径别名起作用,因为它们似乎是与 .d.ts 一代更复杂和独立的问题,如果这成为一个问题,我稍后会在对同一问题的评论中包含

文件结构:

.
├── src/
│   ├── helpers/
│   │   └── parseOptions.ts
│   ├── eswatch.ts
│   └── tsconfig.json
├── package.json
└── tsconfig.json

./tsconfig.json

{
  "compilerOptions": {
    "rootDir": ".",
    "outDir": ".",
    "resolveJsonModule": true,
    "composite": true,
  },
  "files": ["package.json"],
}

./src/tsconfig.json

{
  "compilerOptions": {
    "rootDir": ".",
    "outDir": "../types",
    "resolveJsonModule": true
  },
  "paths": {
    "@eswatch/*": ["./*"]
  },
  "references": [
    { "path": "../" }
  ]
}

在与项目引用结合使用时,根本无法识别路径别名,实际上它们应该正常工作,因此应该发出声明文件

【问题讨论】:

  • 为什么会有 2 个 tsconfig.json ?
  • 由于this answer上的建议
  • 没那么奇怪,它在 monorepo 场景中很常见,除此之外,它是一个内置的typescript feature,所以,它打算在需要时使用,不,我不遵守诸如使用节点原生 fs 模块阅读 package.json 或类似的丑陋黑客之类的事情
  • 为什么要在应用中读取 package.json?
  • 通过-v--version 标志时显示版本字段

标签: typescript alias package.json tsconfig tsc


【解决方案1】:

解决了!事实证明这是一个非常愚蠢的错误,不知何故被忽视了,tsconfig.jsonpaths 属性应该在 compilerOptions 内部,而不是在对象根级别,以下对我有用:

{
  "compilerOptions": {
    "rootDir": ".",
    "outDir": "../types",
    "resolveJsonModule": true,
    "paths": {
       "@eswatch/*": ["./*"]
     }
  },
  "references": [
    { "path": "../" }
  ]
}

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 2017-05-21
    • 2016-11-30
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多