はじめに
Node.js 22 で TypeORM を使ってバックエンドを構築しようとした際に、ESM (ECMAScript Modules) の扱いで様々なエラーに遭遇しました。本記事では、発生したエラーとその解決策をまとめます。
環境
- Node.js: 22.13.1
- TypeORM: 0.3.21
- TypeScript: 5.8.2
発生したエラー
exports is not defined in ES module scope
Cannot find module '/app/dist/data-source' imported from /app/dist/server.js
ERR_UNKNOWN_FILE_EXTENSION: Unknown file extension ".ts" for /app/src/entities/Drug.ts
解決策
1. package.json
の設定
Node.js 22 では ESM を使用する場合、package.json
に "type": "module"
を明示する必要があります。
{
"name": "medilog-backend",
"version": "1.0.0",
"description": "MediLog backend using Express and TypeORM",
"main": "dist/server.js",
"type": "module",
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
},
"dependencies": {
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"mssql": "^11.0.1",
"reflect-metadata": "^0.2.2",
"tsconfig-paths": "^4.2.0",
"typeorm": "^0.3.21"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"ts-node": "^10.9.2",
"ts-node-dev": "^2.0.0",
"typescript": "^5.8.2"
},
}
2. tsconfig.json
の設定
TypeScript のコンパイル設定で module
を NodeNext
に変更し、moduleResolution
も NodeNext
にする。
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"strictPropertyInitialization": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true,
"forceConsistentCasingInFileNames": true,
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
3. import
文の修正
CommonJS (require
) は使えないため、すべて import
に統一する必要があります。
修正前 (CommonJS):
const express = require("express");
修正後 (ESM):
import express from "express";
4. TypeORM の entities
設定
TypeORM の data-source.ts
で entities
のパスを .js
に変える必要があります。
修正前:
entities: ["src/entities/*.ts"],
修正後:
entities: ["dist/entities/*.js"],
まとめ
Node.js 22 で TypeORM を ESM として動かす場合、
-
package.json
に"type": "module"
を追加 -
tsconfig.json
でmodule
とmoduleResolution
をNodeNext
に変更 -
import
文を ESM 準拠に修正 - TypeORM の
entities
パスを.js
に変更
といった対応が必要になります。