spec/test フォルダで tsconfig を設定する 質問する

spec/test フォルダで 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フォルダーにトランスパイルされます。

この問題をどうやって解決すればいいでしょうか?

ベストアンサー1

最終的には複数の設定ファイルを定義し、extendsそれらを簡素化するために使用しました。

2つのファイルがあるとしますtsconfig.jsontsconfig.build.json

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

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

tsc -p tsconfig.build.jsonこうすることで、( を使って) 何をビルドするか、ts language service(IDE) が何を処理するかを細かく制御できます。

更新: プロジェクトが拡大するにつれて、構成ファイルが増えました。TypeScript で利用できるようになった「extend」機能を使用します。

// 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": [ ... ]
 }

おすすめ記事