LoginSignup
5
4

More than 5 years have passed since last update.

TypeORMのmigrationで.tsファイルを直接参照したい

Posted at
  • TypeORM v0.2.6
  • Node.js v10.11.0

TypeORMのmigrationを使うため、公式ドキュメントを参考にrootにormconfig.jsを置いてDB情報を設定

ormconfig.js
module.exports = {
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    database: 'hogehoge',
    username: 'hogehoge',
    password: 'hogehoge',
    entities: ["build/server/database/entities/*.js"], // <- ビルドされたJSファイルを参照している
    subscribers: [],
    migrations: ['migrations/*'],
    cli: {
        migrationsDir: 'migrations',
    },
};

以下のコマンドを実行してmigrationファイルを生成

yarn typeorm migration:generate -n hogehoge

問題なくmigrationファイルが生成された。

ただこれだと、TypeScriptで書いている場合必ずビルドしてから実行しないと定義にずれが生じる可能性があるのでこうしてみた

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

エラーが起きる

(function (exports, require, module, __filename, __dirname) { import {Entity, PrimaryGeneratedColumn} from 'typeorm';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

\(^o^)/

解決策

you node environment tries to load src/entity/User.ts, but it should load .js. So you either need to run app with ts-node, or set proper configuration for JS FILES in your ormconfig cli section, e.g. dist/migrations/.*js

コマンドをこう治すと問題なく動くようになる

ts-node ./node_modules/.bin/typeorm migration:generate -n hogehoge

まあTSファイルはTS実行環境じゃないとだめだよね・・・

5
4
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
5
4