typescriptで新しくパッケージをテストしたいときのdocker環境構築
本記事ではChatGPTを使用して作成しています。一応手順の確認をしましたが、typescriptで新しくパッケージを勉強するときにコンテナで構築して動作を確認したかったのでつくりました。
参考になれば幸いです。
1. プロジェクトの初期設定
package.json
を初期化
プロジェクトディレクトリを作成し、mkdir my-typescript-app
cd my-typescript-app
npm init -y
必要なパッケージをインストール
npm install --save express nodemon neverthrow
npm install --save-dev typescript @types/express @types/node
TypeScript の設定ファイルを生成
npx tsc --init
tsconfig.jsonの修正
tsconfig.jsonを修正します。
{
"compilerOptions": {
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"types": ["node"], /* Specify type package names to be included without being referenced in a source file. */
/* Emit */
"outDir": "./dist", /* Specify an output
/* Interop Constraints */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
/* Completeness */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
Dockerfile
の作成
2. プロジェクトルートに Dockerfile
を作成し、以下の内容を追加します。
# ベースイメージとしてNode.js18を使用する
FROM node:20-alpine
# アプリケーションディレクトリを作成
WORKDIR /usr/src/app
# パッケージの依存関係をインストール
COPY package*.json ./
RUN npm install
# アプリケーションのソースをコピー
COPY . .
# Typescriptをコンパイル
RUN npx tsc
# アプリケーションの起動
CMD ["node", "dist/index.js"]
docker-compose.yml
の作成
3. プロジェクトルートに docker-compose.yml
を作成し、以下の内容を追加します。
services:
app:
build:
context: .
dockerfile: Dockerfile
volumes:
- .:/usr/src/app
ports:
- "3000:3000"
environment:
- NODE_ENV=development
command: sh -c "npm install && npm run dev"
package.json
のスクリプト設定
4. package.json
に以下のスクリプトを追加します。
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/index.js",
"dev": "npx nodemon --watch src --exec \"npm run build && node dist/index.js\"",
"build": "npx tsc"
},
5. TypeScriptコードの作成
例えば、src/index.ts
というファイルを作成し、以下のコードを追加します。
import express from "express";
import { ok, err, Result } from "neverthrow";
const app = express();
const port = 3000;
const exampleFunction = (input: number): Result<number, Error> => {
if (input > 0) {
return ok(input * 2);
} else {
return err(new Error("input must be greater than zero"));
}
};
app.get("/:input", (req, res) => {
const input = parseInt(req.params.input, 10);
const result = exampleFunction(input);
result.match(
(value) => res.send(`<h1>Success: ${value}</h1>`),
(error) => res.status(400).send(`<h1>Error: ${error.message}</h1>`)
);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
6. Dockerコンテナのビルドと起動
以下のコマンドでDockerコンテナをビルドし、バックグラウンドで起動します。
docker-compose up -d
7. 動作確認
ブラウザで http://localhost:3000/5
にアクセスすると、Success: 10
と表示されます。また、http://localhost:3000/-1
にアクセスすると、Error: Input must be greater than zero
と表示されます。
8. パッケージの追加とコンテナの更新
ローカルで必要なパッケージを追加した後、以下のコマンドでコンテナを再起動して更新を反映させます。
npm install <パッケージ名>
docker-compose down
docker-compose up -d
まとめ
この手順を通じて、TypeScriptの開発環境をDockerコンテナ上で構築し、ホットリロードや依存関係の自動更新を利用した効率的な開発が可能になります。package.json
に変更があった場合でも、コンテナを再起動するだけで最新の依存関係が反映されるため、開発効率が向上します。
補足
docker-compose
と .gitignore
ファイルを追加することで、不要なファイルやディレクトリがDockerコンテナやGitリポジトリに含まれないようにできます。これにより、環境をクリーンに保ちつつ、他の開発者と環境を共有することができます。
.dockerignore
ファイル
プロジェクトのルートディレクトリに .dockerignore
ファイルを作成し、以下の内容を追加します。このファイルにより、Dockerビルド時に不要なファイルやディレクトリがコンテナにコピーされるのを防ぎます。
node_modules
dist
.git
.gitignore
Dockerfile
docker-compose.yml
README.md
.gitignore
ファイル
プロジェクトのルートディレクトリに .gitignore
ファイルを作成し、以下の内容を追加します。このファイルにより、不要なファイルやディレクトリがGitリポジトリにコミットされないようにします。
# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json
# TypeScript
dist/
*.tsbuildinfo
# Docker
docker-compose.override.yml
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# IDEs and Editors
.vscode/
.idea/
.DS_Store
# Environment Variables
.env
説明
-
node_modules/
: ローカルでインストールされた依存関係のディレクトリ。これを共有すると冗長なので、.dockerignore
と.gitignore
の両方で除外します。 -
dist/
: TypeScript のコンパイル後の出力ディレクトリ。通常、ビルド成果物は共有する必要がないため除外します。 -
.env
: 環境変数を含むファイル。セキュリティのため、Gitリポジトリには含めない方が良いです。 -
.vscode/
,.idea/
,.DS_Store
: 各開発者のIDEやエディタ固有の設定ファイルやMacのシステムファイル。
これで環境を共有する準備が整いました
この .dockerignore
と .gitignore
ファイルを追加することで、環境がクリーンに保たれ、無駄なファイルがコンテナやリポジトリに含まれなくなります。これで、他の開発者と環境を安全かつ効率的に共有することが可能です。
何か他に質問があれば、どうぞお知らせください。
Discussion