typeorm: Migration cli unexpected token import

I wrote everything in typescript. The application and everything work fine, but as soon as I call

typeorm migrations:run

I get this error

src/entity/User.ts:1 (function (exports, require, module, __filename, __dirname) { import {Entity, Column, PrimaryGeneratedColumn} from “typeorm”; ^^^^^^ SyntaxError: Unexpected token import at Object.exports.runInThisContext (vm.js:78:16) at Module._compile (module.js:543:28) at Object.Module._extensions…js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at Function.PlatformTools.load (/usr/local/lib/node_modules/typeorm/platform/PlatformTools.js:26:20) at /usr/local/lib/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:29:69 (node:38469) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 5): SyntaxError: Unexpected token import (node:38469) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Not sure if it matters but this is my tsconfig.json:

{ “compilerOptions”: { “declaration”: true, “emitDecoratorMetadata”: true, “experimentalDecorators”: true, “isolatedModules”: false, “module”: “commonjs”, “moduleResolution”: “node”, “outDir”: “dist”, “sourceMap”: true, “sourceRoot”: “src”, “noEmitHelpers”: false, “target”: “es5”, “typeRoots”: [ “node_modules/@types” ], “lib”: [“es6”, “dom”] }, “exclude”: [ “node_modules” ] }

What ever I change in tsconfig.json seems to not effect the error at all.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 8
  • Comments: 29 (3 by maintainers)

Most upvoted comments

Anyone wondering about this, you must run your .ts files thru ts-node first.

Simply:

>> ./node_modules/.bin/ts-node ./node_modules/.bin/typeorm <command>

it’s surprising that typeorm cli doesn’t work with typescript by default without asking user to explicitly pass through ts-node. Is that something which could be built in given how typeorm itself is written in typescript?

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

Also, in Win 10 works: ts-node node_modules\typeorm\cli.js

after long I installed ts-node and typescript globally and use ts-node ./node_modules/typeorm/cli.js migration:generate -n MigrationName command things start to work. then added these to package.json

{
  /* ... */
  "scripts": {
  /* ... */
    "typeorm-migration-generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n MigrationName",
    "typeorm-migration-run": "ts-node ./node_modules/typeorm/cli.js migration:run",
    "typeorm-migration-revert": "ts-node ./node_modules/typeorm/cli.js migration:revert"
  }
}

now i can just run npm run typeorm-migration-run and others

@davidmpaz

I used this command ./node_modules/.bin/ts-node ./node_modules/.bin/typeorm schema:sync

for es project in win 10

.\node_modules\.bin\babel-node .\node_modules\typeorm\cli.js schema:sync

If you are using ormconfig.json file, it should look like:

{
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "root",
    "password": "password",
    "database": "persona_db",
    "entities": [
        "dist/**/*.entity{.ts,.js}"
    ],
    "synchronize": false,
    "migrations": [
        "dist/migrations/**/*{.ts,.js}"
    ],
    "cli": {
        "migrationsDir": "migrations"
    }
}

NOTE: Please refer to the “dist” folder and not the root folder…

Hi @stormpat,

thanks for the hint. Still is not working for me.

./node_modules/.bin/ts-node ./node_modules/.bin/typeorm schema:log

gives me still:

import { Column, Entity, ManyToOne } from 'typeorm';
^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Module.m._compile (/srv/http/is7/mobile-sdk/src/modules/products/node_modules/ts-node/src/index.ts:422:23)
    at Module._extensions..js (module.js:654:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/srv/http/is7/mobile-sdk/src/modules/products/node_modules/ts-node/src/index.ts:425:12)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Module.require (module.js:587:17)

Any idea ?

did you resolve your issue?

"entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],

我遇到了同样 的 问题在将 ormconfig.json中的 ts 改为 js之后解决了问题

I found a way to make migratons work with my ionic 3 application. NO NEED TO EXPLICITLY PASS TS-NODE In ormconfig.json:

{
    "cli": {
        "migrationsDir": "src/migrations/"
    }
}

and the connection:

 await createConnection({
            type: 'cordova',
            database: 'test',
            location: 'default',
            logging: ['error', 'query', 'schema'],
            synchronize: false,
            entities: [
                //entities
            ],
            migrations:[
                //migrations generated by typeorm cli
            ],
            migrationsRun: true
        }).catch(err => console.log("error: ", err));

tsconfig.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "src/**/*.spec.ts",
    "src/**/__tests__/*.ts"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

@willianfalbo I ran into a similar issue with deploying the compiled js code to server. I was very confused how any ts file was referenced to the compiled code. Didn’t even think about checking ormconfig.json…Thanks so much!!!

Using ENV variables, the fix for me was

TYPEORM_ENTITIES=dist/**/*.entity.js
TYPEORM_MIGRATIONS=dist/migration/*.js
TYPEORM_MIGRATIONS_DIR=dist/migration

Hope this helps someone

I had a similar issue when running my JavaScript application code (which has been transpiled from TypeScript):

(function (exports, require, module, __filename, __dirname) { import {Column, Entity, PrimaryGeneratedColumn} from “typeorm”;

SyntaxError: Unexpected token {

I solved it by pointing the entities in my ormconfig.js to my compiled JavaScript code. Before that (when I had the error) they have been linked to my TypeScript source code.

This configuration now works for me:

ormconfig.js

const ConnectionOptions = {
  cli: {
    entitiesDir: 'src/main/entity',
    migrationsDir: 'src/migration',
    subscribersDir: 'src/subscriber',
  },
  database: 'database/development.db3',
  entities: ['dist/entity/*.js'],
  logging: false,
  migrations: ['src/migration/**/*.ts'],
  subscribers: ['src/subscriber/**/*.ts'],
  synchronize: true,
  type: 'sqlite',
};

if (process.env.NODE_ENV === 'production') {
  ConnectionOptions.database = 'database/production.db3';
}

if (process.env.NODE_ENV === 'test') {
  ConnectionOptions.database = 'database/test.db3';
}

module.exports = ConnectionOptions;