TypeScriptプロジェクトを効率的にビルドするためには、適切なビルドツールの選択と設定が重要です。この記事では、主要なビルドツールであるwebpack、Rollup、Parcelとの連携方法と、ts-loaderの設定について詳しく解説します。

webpackとTypeScriptの連携

webpackでTypeScriptを使用するには、主に2つの方法があります:

1. ts-loaderを使用する方法

// webpack.config.js
module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  }
};

2. babel-loaderとTypeScriptプラグインを組み合わせる方法

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-typescript']
          }
        }
      }
    ]
  }
};

Rollupとの連携

Rollupでは、@rollup/plugin-typescriptを使用します:

// rollup.config.js
import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs'
  },
  plugins: [
    typescript({
      tsconfig: './tsconfig.json'
    })
  ]
};

Parcelとの連携

Parcelは特別な設定なしでTypeScriptをサポートしています。以下の手順で設定できます:

1. 必要なパッケージのインストール

npm install --save-dev parcel @parcel/transformer-typescript-tsc

2. package.jsonにParcel設定を追加

{
  "source": "src/index.ts",
  "scripts": {
    "start": "parcel",
    "build": "parcel build"
  }
}

ts-loaderの詳細設定

ts-loaderをより効率的に使用するための設定例:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: 'ts-loader',
          options: {
            // トランスパイルのみを行い、型チェックを省略
            transpileOnly: true,
            // 並列処理を有効化
            happyPackMode: true,
            // カスタムコンパイラオプション
            compilerOptions: {
              sourceMap: true
            }
          }
        }
      }
    ]
  }
};

パフォーマンス最適化のヒント

1. キャッシュの活用

// webpack.config.js
{
  cache: {
    type: 'filesystem'
  }
}

2. 並列処理の有効化

// webpack.config.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
  plugins: [
    new ForkTsCheckerWebpackPlugin()
  ]
};

トラブルシューティング

よくある問題と解決策:

1. モジュール解決エラー

// tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}

2. パスエイリアスの設定

// webpack.config.js
{
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
}

これらの設定を適切に組み合わせることで、効率的なTypeScriptの開発環境を構築できます。プロジェクトの規模や要件に応じて、最適なツールと設定を選択してください。