0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.js 22 + TypeORM (ESM) でハマった

Posted at

はじめに

Node.js 22 で TypeORM を使ってバックエンドを構築しようとした際に、ESM (ECMAScript Modules) の扱いで様々なエラーに遭遇しました。本記事では、発生したエラーとその解決策をまとめます。

環境

  • Node.js: 22.13.1
  • TypeORM: 0.3.21
  • TypeScript: 5.8.2

発生したエラー

  1. exports is not defined in ES module scope
  2. Cannot find module '/app/dist/data-source' imported from /app/dist/server.js
  3. 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 のコンパイル設定で moduleNodeNext に変更し、moduleResolutionNodeNext にする。

{
  "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.tsentities のパスを .js に変える必要があります。

修正前:

entities: ["src/entities/*.ts"],

修正後:

entities: ["dist/entities/*.js"],

まとめ

Node.js 22 で TypeORM を ESM として動かす場合、

  • package.json"type": "module" を追加
  • tsconfig.jsonmodulemoduleResolutionNodeNext に変更
  • import 文を ESM 準拠に修正
  • TypeORM の entities パスを .js に変更

といった対応が必要になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?