実際の開発では、コードをバンドルするためにビルドツールが必須です。TypeScriptも例外ではなく、webpackなどのビルドツールと組み合わせて使用します。ここでは、webpackを例にTypeScriptプロジェクトの設定方法を詳しく解説します。
プロジェクトの初期化
まず、以下のコマンドで新しいプロジェクトを初期化し、package.jsonを生成します。
npm init -y
TypeScriptの設定ファイルであるtsconfig.jsonを作成します。
tsc --init
srcディレクトリを作成し、その中にmain.tsファイルを配置してTypeScriptコードを記述します。
ビルドツールの導入
必要なパッケージのインストール
webpack本体と関連ツールをインストールします。
npm i -D webpack webpack-cli webpack-dev-server
- webpack: モジュールバンドラー本体
- webpack-cli: webpackのコマンドラインインターフェース
- webpack-dev-server: 開発用サーバー
TypeScriptをコンパイルするためのローダーをインストールします。
npm i -D ts-loader typescript
- typescript: TypeScriptコンパイラ
- ts-loader: webpackでTypeScriptを処理するローダー
HTML生成とクリーニングのためのプラグインをインストールします。
npm i -D html-webpack-plugin clean-webpack-plugin
- html-webpack-plugin: HTMLファイルを自動生成
- clean-webpack-plugin: ビルド前に出力ディレクトリをクリーンアップ
webpackの基本設定
ルートディレクトリにwebpack.config.jsを作成し、基本設定を記述します。
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./src/main.ts",
devtool: "source-map",
devServer: {
static: "./dist",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "main.js",
environment: {
arrowFunction: false,
},
},
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "./src/template.html",
}),
],
};
環境別設定の分割
実際の開発では開発環境と本番環境で設定を分けることが推奨されます。webpack-mergeを使用して設定を分割管理します。
npm i -D webpack-merge
buildディレクトリを作成し、設定ファイルを分割します。
webpack.common.js (共通設定):
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/main.ts",
output: {
path: path.resolve(__dirname, "../dist"),
filename: "bundle.js",
},
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html",
}),
],
};
webpack.dev.js (開発環境):
module.exports = {
mode: "development",
devtool: "eval-source-map",
devServer: {
static: "./dist",
hot: true,
},
};
webpack.prod.js (本番環境):
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
mode: "production",
plugins: [new CleanWebpackPlugin()],
};
webpack.config.js (メイン設定):
const { merge } = require("webpack-merge");
const commonConfig = require("./build/webpack.common");
const devConfig = require("./build/webpack.dev");
const prodConfig = require("./build/webpack.prod");
module.exports = (env, argv) => {
const config = argv.mode === "development" ? devConfig : prodConfig;
return merge(commonConfig, config);
};
TypeScriptの設定
tsconfig.jsonを以下のように設定します。
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["DOM", "ES2020"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
サンプルコードの実装
src/main.ts:
const container = document.getElementById('root') as HTMLElement;
const message: string = 'TypeScript + webpack';
if (container) {
container.textContent = message;
}
src/template.html:
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TypeScript + Webpack</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
実行コマンドの設定
package.jsonにスクリプトを追加します。
{
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production"
}
}
以下のコマンドで開発サーバーを起動または本番ビルドを実行できます。
npm run dev # 開発サーバー起動
npm run build # 本番ビルド
Babelの統合
ブラウザ互換性を高めるためにBabelを導入します。
Babel関連パッケージのインストール
npm i -D @babel/core @babel/preset-env babel-loader core-js
- @babel/core: Babelのコア機能
- @babel/preset-env: ターゲットブラウザに応じた変換
- babel-loader: webpackでのBabel実行
- core-js: ポリフィル提供
webpack設定の更新
webpack.common.jsのmodule.rulesを更新します。
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: "babel-loader",
options: {
presets: [
[
"@babel/preset-env",
{
targets: {
browsers: ["> 1%", "last 2 versions", "not ie <= 11"]
},
corejs: 3,
useBuiltIns: "usage"
}
]
]
}
},
"ts-loader"
],
exclude: /node_modules/
}
]
}
これでTypeScriptのコードがBabelによってターゲットブラウザに合わせて最適化され、より広範な環境で動作するようになります。