LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript + Express】 "npm run dev"でError: Cannot find module が出たら

Last updated at Posted at 2022-07-12

こんにちは。

Qiita1発目の記事を何にしようかと悩んでいたのですが、ちょうど
「TypeScriptでバックエンドつくってみよー」
と、半分軽い気持ちで作っていたら見事ハマったので備忘録。

nodemonからts-node-devに変更し、package.jsonでパスエイリアスをフルパスで表記したら、エラーが発生しなくなったので紹介する。

※ts-nodeがインストールされていることが前提条件

何にハマったのか

REST APIをnodemonで実行したら、モジュールエラーが発生した。

エラー文は以下。

Error: Cannot find module './index.ts'

解決法

1. 「npm uninstall nodemon」でアンインストール。

→解決方法とまではいかないが、理由としてはモダンなツールではないらしいので。 というよりも、ググって出てきた方法では解決できなかった。

2. 「npm i ts-node-dev」でインストール

→これがnodemonよりモダンらしいので導入。

3. 「npm i --save-dev tsconfig-paths」もインストール

→これも一緒にインストールしないと、パスエイリアスが通らないのでインストール。

4. 「package.json」に追記

package.json
"scripts": {
   "start": "ts-node -r tsconfig-paths/register ~/ディレクトリ名/index.ts",
   "dev": "ts-node-dev -r tsconfig-paths/register ~/ディレクトリ名/index.ts",
   "build": "tsc"
}

上記のように、「ディレクトリ名」の前にホームディレクトリを表す「~/」から、フルパスで記入した。
この方法で、実行時の「Error: Cannot find module」のエラーは発生しなくなった。

環境

クライアントOS: macOS Monterey 12.04

サーバーOS: Linux (debian10)

ts-node-dev: ver2.0.0
ts-node: ver10.8.2
typescript: ver4.7.4

参考

ts-node で path alias が効かないにハマる
https://chaika.hatenablog.com/entry/2021/12/20/083000

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