LoginSignup
2
1

More than 1 year has passed since last update.

TypeScript: ビルド対象から除外するファイルを指定する方法

Posted at

概要

アプリケーションを開発していると、単体テストなどアプリケーション以外のコードを書くことがあると思います。

アプリケーションコードとそれ以外のコードを分けて扱う仕組みは言語やフレームワークによってサポートされていることが多いと思いますが、TypeScriptでも同様の仕組みが用意されています。

この記事ではTypeScriptで書かれたコードをビルドするときに、ビルド対象から除外するファイルを指定する方法を紹介します。

環境

$npx tsc -v
Version 4.5.4

課題

以下のような構成のプロジェクトで、
__tests__配下をビルド対象から除外する場合について考えてみようと思います。

├── dist
├── src
│   ├── __tests__
│   │   └── index.test.ts
│   └── index.ts
└── tsconfig.json

コンパイラの設定は仮に以下のようにしておきます。
src配下のコードをビルドして、結果をdist配下に出力します。

tsconfig.json
{
    "compilerOptions": {
        "target": "es2016",
        "module": "commonjs",
        "rootDir": "./src",
        "sourceMap": true,
        "outDir": "./dist",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true
    },
}

この状態でビルドすると以下のように__tests__配下もコンパイルされます。
デフォルトでは全ての.tsファイルがビルドの対象になります。

├── dist
│   ├── __tests__
│   │   ├── index.test.js
│   │   └── index.test.js.map
│   ├── index.js
│   └── index.js.map
├── src
├── __tests__
│   │   └── index.test.ts
│   └── index.ts
└── tsconfig.json

解決策

コンパイラの設定(tsconfig.json)に以下を追加します。

{
    "compilerOptions": {
        "target": "es2016",
        "module": "commonjs",
        "rootDir": "./src",
        "sourceMap": true,
        "outDir": "./dist",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true
    },
    "exclude": ["src/**/__tests__/*"] <- これを足す
}

ビルド結果は以下のようになります。

├── dist
│   ├── index.js
│   └── index.js.map
├── src
├── __tests__
│   │   └── index.test.ts
│   └── index.ts
└── tsconfig.json

__tests__配下が出力されなくなりました。

留意事項

excludeを指定する場合には以下の点に留意する必要があります。

  1. ビルド対象から外したファイルを編集する場合
    VSCodeの場合は、プロジェクト内の他のモジュールをインポートしようとしたときに、自動インポートや入力補完が動作しなくなるようです。
    インポートできないわけではありませんが、全て手動で入力する必要があります。

  2. ビルド対象のファイルからビルド対象外のファイルをインポートする場合
    ビルド対象外だったファイルもビルドされます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1