【问题标题】:Typescript configuration with src and test带有 src 和测试的打字稿配置
【发布时间】:2021-06-11 05:08:37
【问题描述】:

我有多个 TypeScript 项目,我将源代码与测试分开到它们的目录(srctest)。在最终包中,我想只包含不包含测试的源代码,因为运行时不需要知道任何关于测试文件、夹具等的信息。

如果我在tsconfig.json中有如下设置:

{
  "compilerOptions": {
    // compiler options
    "outDir": "dist"
  },
  "include": ["src"]
}

这些在package.json:

{
  // usual settings
  "main": "dist/index.js",
  "files": [
    "dist/**/*.js",
    "dist/**/*.d.ts"
  ]
}

那么最终的包只包含所需目录结构中的源代码,这是我想看到的,但是我的环境有问题。我正在使用Doom Emacs 并且对于测试潮会抛出这样的错误:

Error from syntax checker typescript-tide: Error processing request. No Project.
Error: No Project.
    at Object.ThrowNoProject (/Users/ikaraszi/.../node_modules/typescript/lib/tsserver.js:152133:23)

如果我将tsconfig.json 设置更改为包含test 目录,那么潮汐错误就会消失:

{
  "compilerOptions": {
    // compiler options
    "outDir": "dist",
    "rootDirs": ["src", "test"]
  }
}

但是随后分发的目录结构发生了变化,我想避免出现 dist/srcdist/test,因为那时我的库的用户将需要使用奇怪的导入语句:

import { foo } from 'library/dist/src/foo';

如果可能的话,我想避免额外的srcdist 已经够丑了,但这是给定的。

我尝试使用多个设置将include 属性更改为具有srctest,但构建最终位于具有相同嵌套结构的dist 目录中:

{
  "compilerOptions": {
    // compiler options
    "outDir": "dist"
  },
  "include": ["src", "test"]
}

我还尝试使用package.json 设置,但没有任何运气。如果不向构建过程添加额外步骤以删除不必要的额外目录,我能做些什么吗?

【问题讨论】:

  • 通常您也希望在测试中使用不同的类型,因此您有第二个tsconfig.test.json 扩展tsconfig.json 并引入额外的类型和文件。不过,我不熟悉潮汐(或 emacs!),快速浏览文档似乎并不能表明您可以将其配置为查看 tsconfig.json 以外的任何内容。
  • 如果我切换它,这个解决方案可以工作。我会有一个带有构建设置的tsconfig.build.json 和一个包含源代码和测试的tsconfig.json

标签: typescript npm emacs tsconfig


【解决方案1】:

根据@jonrsharpe 的评论,我最终得到了两个 tsconfig 文件:

tsconfig.json:

{
  "extends": "@tsconfig/node14/tsconfig.json",
  "compilerOptions": {
    "declaration": true,
    "outDir": "dist",
    "sourceMap": false,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "allowSyntheticDefaultImports": true,
    "noUnusedLocals": false,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src", "test"]
}

还有一个tsconfig.build.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "target": "es2018",
    "noUnusedLocals": true
  },
  "include": ["src"]
}

而在package.json

{
  // usual settings
  "main": "dist/index.js",
  "files": [
    "dist/**/*.js",
    "dist/**/*.d.ts"
  ],
  "scripts": {
    "build": "tsc --build tsconfig.build.json",
    // other scripts
  }
}

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 1970-01-01
    • 2019-01-30
    • 2017-05-14
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多