typescript - 使用 spec/test 文件夹设置 tsconfig

标签 typescript visual-studio-code tsconfig

假设我将我的代码放在 src 下并在 spec 下进行测试:

+ spec
+ --- classA.spec.ts
+ src
+ --- classA.ts
+ --- classB.ts
+ --- index.ts
+ tsconfig.json

我只想将 src 转译到 dist 文件夹。因为 index.ts 是我的包的入口点,所以我的 tsconfig.json 看起来像这样:

{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "files": {
    "src/index.ts",
    "typings/main.d.ts"
  }
}

但是,此 tsconfig.json 不包含测试文件,因此我无法解析其中的依赖关系。

另一方面,如果我将测试文件包含到 tsconfig.json 中,那么它们也会被转译到 dist 文件夹中。

我该如何解决这个问题?

最佳答案

我最终定义了多个配置文件并使用 extends 来简化它们。

假设我有两个文件:tsconfig.jsontsconfig.build.json

// tsconfig.json
{
  ...
  "exclude": [...]
}

// tsconfig.build.json
{
  ...
  "files": [ "typings/index.d.ts", "src/index.ts" ]
}

这样,我可以很好地控制要构建的内容(使用 tsc -p tsconfig.build.json)以及 ts 语言服务 (IDE) 处理的内容.

更新:现在随着我的项目的增长,我最终拥有了更多的配置文件。我使用 TypeScript 中现在可用的“扩展”功能:

// tsconfig.base.json
{
  // your common settings. Mostly "compilerOptions".
  // Do not include "files" and "include" here,
  // let individual config handles that.
  // You can use "exclude" here, but with "include",
  // It's pretty much not necessary.
}

// tsconfig.json
{
  // This is used by `ts language service` and testing.
  // Includes source and test files.
  "extends": "./tsconfig.base.json",
  "atom": { ... },
  "compilerOptions": {
    // I set outDir to place all test build in one place,
    // and avoid accidentally running `tsc` littering test build to my `src` folder.
    "outDir": "out/spec"  
  }
  "include": [ ... ]
}

// tsconfig.commonjs.json or tsconfig.systemjs.json or tsconfig.global.json etc
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    // for some build this does not apply
    "declaration": true/false,
    "outDir": "dist/<cjs, sys, global, etc>",
    "sourceRoot": "..."
  },
  // Only point to typings and the start of your source, e.g. `src/index.ts`
  "files": [ ... ],
  "include": [ ... ]
 }

关于typescript - 使用 spec/test 文件夹设置 tsconfig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470511/

相关文章:

Typescript 目标为 es6 和 es2015

angular - 在移动设备上显示 Accordion 并在其他设备上显示标签

node.js - 导入带有导出枚举的模块时找不到模块错误

python - 在 VS Code 中本地调试多个 Python Azure 函数

typescript - tsconfig.json 中的目标是什么?

html - 尝试在样式中插入 typescript 元素时出现术语预期错误

logging - Visual Studio Code 不显示控制台日志

javascript - VSCode 不会对模板字符串内的内容进行样式设置

angular - typescript :即使正确解析了导入,IntelliJ 也会在导入时显示错误