tsconfig.json ファイルを使って Node.js + TypeScript で環境変数を使う
Node.js + TypeScript で process.env を使う方法
型定義ファイルの作成
env.d.ts
という名前のファイルを作成し、以下のコードを追加します。
declare global {
namespace NodeJS {
interface ProcessEnv {
// 環境変数の型定義
PORT: number;
DB_HOST: string;
API_KEY: string;
}
}
}
この例では、PORT
、DB_HOST
、API_KEY
という環境変数を定義しています。それぞれの変数の型は、number
、string
、string
としています。
環境変数の読み込み
環境変数は .env
ファイルなどから読み込む必要があります。.env
ファイルは、プロジェクトのルートディレクトリに配置する必要があります。
.env
ファイルの例:
PORT=3000
DB_HOST=localhost
API_KEY=secret-key
環境変数をコードで読み込むには、process.env
オブジェクトを使用します。
const port = process.env.PORT;
const dbHost = process.env.DB_HOST;
const apiKey = process.env.API_KEY;
console.log(`port: ${port}`);
console.log(`dbHost: ${dbHost}`);
console.log(`apiKey: ${apiKey}`);
上記のコードでは、process.env
オブジェクトから PORT
、DB_HOST
、API_KEY
という環境変数を取得し、それぞれ port
、dbHost
、apiKey
という変数に代入しています。
型チェック
型定義ファイルを作成することで、コード内で環境変数の型をチェックできます。
if (typeof port !== 'number') {
throw new Error('PORT is not a number');
}
if (typeof dbHost !== 'string') {
throw new Error('DB_HOST is not a string');
}
if (typeof apiKey !== 'string') {
throw new Error('API_KEY is not a string');
}
上記のコードでは、port
、dbHost
、apiKey
という変数の型が定義されていることを確認しています。型が一致しない場合は、エラーが発生します。
その他のライブラリ
dotenv
などのライブラリを使用することで、.env
ファイルの読み込みや環境変数の型定義をより簡単にできます。
補足
- 上記は Node.js + TypeScript で
process.env
を使う方法の基本的な例です。 - 環境変数の読み込みや型定義には、様々な方法があります。
env.d.ts
declare global {
namespace NodeJS {
interface ProcessEnv {
PORT: number;
DB_HOST: string;
API_KEY: string;
}
}
}
index.ts
import * as dotenv from 'dotenv';
dotenv.config();
const port = process.env.PORT;
const dbHost = process.env.DB_HOST;
const apiKey = process.env.API_KEY;
console.log(`port: ${port}`);
console.log(`dbHost: ${dbHost}`);
console.log(`apiKey: ${apiKey}`);
if (typeof port !== 'number') {
throw new Error('PORT is not a number');
}
if (typeof dbHost !== 'string') {
throw new Error('DB_HOST is not a string');
}
if (typeof apiKey !== 'string') {
throw new Error('API_KEY is not a string');
}
.env
PORT=3000
DB_HOST=localhost
API_KEY=secret-key
実行方法
$ npm install dotenv
$ node index.ts
出力結果
port: 3000
dbHost: localhost
apiKey: secret-key
- このコードは、
dotenv
ライブラリを使って.env
ファイルを読み込んでいます。 .env
ファイルは、プロジェクトのルートディレクトリに配置する必要があります。- 環境変数は
.env
ファイルに記述する必要があります。 - コードを実行する前に、
dotenv
ライブラリをインストールする必要があります。
process.env を使う他の方法
dotenv ライブラリ
import * as dotenv from 'dotenv';
dotenv.config();
const port = process.env.PORT;
const dbHost = process.env.DB_HOST;
const apiKey = process.env.API_KEY;
console.log(`port: ${port}`);
console.log(`dbHost: ${dbHost}`);
console.log(`apiKey: ${apiKey}`);
tsconfig.json
ファイルに env
オプションを追加することで、環境変数を TypeScript の型システムで使用できます。
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": [
"es5",
"dom",
"es2015",
"es2016",
"es2017",
"es2018",
"es2019",
"es2020",
"es2021",
"es2022",
"esnext"
],
"noImplicitAny": false,
"strictNullChecks": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"rootDir": "./src",
"outDir": "./dist",
"baseUrl": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"inlineSources": true,
"removeComments": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"jsx": "react",
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"module": "commonjs",
"lib": [
"es5",
"dom",
"es2015",
"es2016",
"es2017",
"es2018",
"es2019",
"es2020",
"es2021",
"es2022",
"esnext"
],
"noImplicitAny": false,
"strictNullChecks": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"rootDir": "./src",
"outDir": "./dist",
"baseUrl": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"inlineSources": true,
"removeComments": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"jsx": "react",
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"env": {
"NODE_ENV": "development"
}
}
}
手動で型定義
process.env
オブジェクトを直接型定義することもできます。
interface Env {
PORT: number;
DB_HOST: string;
API_KEY: string;
}
const env: Env = process.env
node.js typescript