MeWrite Docs

Cannot find module or its corresponding type declarations

TypeScriptでモジュールや型定義が見つからない場合のエラー

概要

Cannot find module は、TypeScriptがインポートしようとしているモジュールや型定義ファイルを見つけられない場合に発生するエラーです。

エラーメッセージ

TS2307: Cannot find module 'lodash' or its corresponding type declarations.
TS2307: Cannot find module './utils' or its corresponding type declarations.

原因と解決策

1. 型定義がインストールされていない

1
2
3
4
# パッケージはあるが型定義がない場合
npm install --save-dev @types/lodash
npm install --save-dev @types/node
npm install --save-dev @types/express

2. パッケージ自体がインストールされていない

1
npm install lodash

3. パスエイリアスの設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"]
    }
  }
}
1
2
// 使用例
import { Button } from '@components/Button';

4. 相対パスの問題

1
2
3
4
5
6
7
8
// NG: 拡張子が間違っている
import { utils } from './utils.ts';

// OK: 拡張子なし
import { utils } from './utils';

// OK: .js拡張子(ESModules)
import { utils } from './utils.js';

5. カスタム型定義ファイルを作成

1
2
3
4
// types/custom-module.d.ts
declare module 'custom-module' {
  export function doSomething(): void;
}
1
2
3
4
5
6
// tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["./types", "./node_modules/@types"]
  }
}

6. モジュール解決の設定

1
2
3
4
5
6
7
8
// tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    // または Node16/NodeNext(ESM対応)
    "moduleResolution": "node16"
  }
}

7. JSONモジュールのインポート

1
2
3
4
5
6
7
// tsconfig.json
{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}
1
import data from './data.json';

デバッグ方法

1
2
# TypeScriptのモジュール解決をトレース
npx tsc --traceResolution | grep "Module name"

関連エラー

関連エラー

TypeScript の他のエラー

最終更新: 2025-12-17