LoginSignup
0
1

More than 3 years have passed since last update.

NestJS+TypeORM Cannot use import statement outside a moduleエラー distディレクトリが原因だった

Posted at

状況

NestJS+TypeORM構成で、マイグレーションなど諸々実行した後に開発を始めようとnest startすると以下のエラーが発生。

../src/db/migrations/1621141317805-init.ts:1
import {MigrationInterface, QueryRunner} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:992:16)
    at Module._compile (internal/modules/cjs/loader.js:1040:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Module.require (internal/modules/cjs/loader.js:965:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at .../node_modules/typeorm/util/DirectoryExportedClassesLoader.js:41:39
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories (.../node_modules/typeorm/util/DirectoryExportedClassesLoader.js:41:10)

ちなみにormconfigファイルはtsファイルにしていて、entity, migration, factory, seedなど諸々tsファイルにしている。
設定ファイルのファイル読み込みはこんな感じ

ormconfig.ts
entities: ['src/db/entities/**/*{.ts,.js}'],
migrations: ['src/db/migrations/**/*{.ts,.js}'],

以下を参考にjsを読み込ませるように〜, __dirnameをつかって〜など、色々試したが設定ファイル(ormconfig)云々で解決する感じはなかった。

結論

$ rm -rf dist

distディレクトリに過去のmigration情報がたくさん残っていて、これらが影響を与えていたらしい。

自分がサーバー起動前にdbを初期化するときにmigrationディレクトリごと毎回rm -rf ...で削除してたのでdistに過去のmigrationファイルが溜まり続けていることに気づかなかった。

db_init
$ yarn typeorm schema:drop;
$ rm -rf src/db/migrations/*;
$ yarn yarn typeorm migration:generate -n init;
$ yarn yarn typeorm migration:run;

typeorm周りの整備でormconfig.tsに拡張子変えてみたり、関連ファイルいじりまくったりしていて過去のmigrationファイルがよくわかんない状態で残っていたのだと思う。

0
1
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
1