LoginSignup
2
2

More than 1 year has passed since last update.

error TS2307: Cannot find moduleが出た時の対処方法

Last updated at Posted at 2023-03-11

エラー文の通り、何かしらの原因でtypescriptコンパイラがソースファイルを見つけられていない、という事象が起きています。

なので、typescriptコンパイラが「どういう考えで」「どのパス」に対象のソースファイルを探しに行っているのかを知ることが出来れば、原因が特定できそうです。

コンパイラのファイル探しの挙動を見る方法

下記のどちらかを行うことで、typescriptコンパイラのファイル探しの挙動をみることが出来ます。(参考

  • tscでコンパイル時に--traceResolutionオプションを付ける
  • tsconfig.jsontraceResolutiontrueに設定しコンパイルする

このようなログが出るようになります↓

======== Resolving module './infra/logger/LoggerModule.js' from '/app/AppModule.ts'. ========
Step #0: Explicitly specified module resolution kind: 'Node16'.
Step #0: Resolving in ESM mode with conditions 'node', 'import', 'types'.
Step #0: Loading module as file / folder, candidate module location '/app/infra/logger/LoggerModule.js', target file type 'TypeScript'.
Step #0: File name '/app/infra/logger/LoggerModule.js' has a '.js' extension - stripping it.
Step #0: File '/app/infra/logger/LoggerModule.ts' exist - use it as a name resolution result.
Step #0: ======== Module name './infra/logger/LoggerModule.js' was successfully resolved to '/app/infra/logger/LoggerModule.ts'. ========

/app/AppModule.tsでimportされている./infra/logger/LoggerModule.jsについて、Node16というモジュール解決方法に従って/app/infra/logger/LoggerModule.tsというパスを探しに行っていることが分かります。

疑うポイント

下記以外にも疑うポイントたくさんあると思います!切り分けていきましょう!

コンパイラ設定は合っているが対象ファイルがない

  • npm install / yarn install忘れていませんか?
  • ファイル名の大文字小文字だけを変えた場合、その改名がgit commitできていますか?

対象ファイルはあるがコンパイラ設定が誤っている

ちなみに僕は「ファイル名の大文字小文字だけを変えた」時に改名がgit commitできておらず、ローカルではビルド成功するのにCDでだけ落ちており、数時間詰まりました。ファ●ク

2
2
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
2
2