Typeorm: [question] migration cannot recongnize keyword `import`?

Created on 26 Jul 2017  路  53Comments  路  Source: typeorm/typeorm

After setting up ormconfig.json, I use typeorm migrations:create -n base to create migration file. But when I run typeorm migrations:run, it seems cannot recognize the key word import.

ormconfig.json

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "dinfer",
    "password": "dinfer",
    "database": "haodf",
    "logging": {
        "logOnlyFailedQueries": true
    },
    "autoSchemaSync": false,
    "migrations": [
        "src/models/migrations/*.ts"
    ],
    "cli": {
        "migrationsDir": "src/models/migrations"
    }
}

the migration script

import { ColumnSchema, MigrationInterface, QueryRunner, TableSchema } from 'typeorm';

export class IncreaseDoctorSkillLength1501091244552 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(new TableSchema('a', [
            new ColumnSchema({ name: 't', type: 'string', length: 1000 })
        ]))
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable('a')
    }

}

the output

```PS E:workcrawlerspider> typeorm migrations:run
Error during migration run:
E:crawlerspidersrcmodelsmigrations1501091244552-base.ts:1
(function (exports, require, module, __filename, __dirname) { import { ColumnSchema, MigrationInterface, QueryRunner, TableSchema } from 'typeorm';
^^^^^^

SyntaxError: Unexpected token import
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Function.PlatformTools.load (C:UsersdinferAppDataRoamingnpmnode_modulestypeormplatformPlatformTools.js:28:20)
PS E:workcrawlerspider>


tsconfig.json

{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"rootDir": "./src",
"strict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}


`npm ls -g --depth=0`

+-- [email protected]
```

question

Most helpful comment

Had same problem, solved by having:
"migrate": "ts-node ./node_modules/.bin/typeorm migrations:generate"
in the scripts section of package.json and then doing:
npm run migrate -- --name InitialMigration

All 53 comments

try to run js files instead of ts, e.g.:

    "migrations": [
        "src/models/migrations/*.js" // make sure to specify outdir if you are using outdir
    ]

Indeed it's the same for the entities and any other that is requested from cli commands (Like on typeorm schema:sync), i think there should be a feat to allow using the ts files, shouldn't be that hard, just telling the cli to use ts-node to execute such task.

Maybe i'm over simplifying since idk the internals of the CLI, but i think since this repo already promotes typescript as the defacto target environment, why not going all the way?

thanks you all.

Running migrations over compiled files works fine.

Just like what @luchillo17 said, supporting typescript file maybe better.

having ts-node in dependency is overhead (and as I remember there are some issues with ts-node if its not installed globally). We probably need some more simplified way

Though we don't yet know which will that simplified way be, right?, for the time being i guess we could just use tsc in watch mode, as a workaround.

Btw could you point me where does the ts-node global dependency issue info, report or discussion are? i was unaware of such, would like to know more.

Also how does Gulp about it? i have a Typescript gulpfile and it works flawlessly just by me adding gulp to my dependencies.

Refer to: http://blog.jonasbandi.net/2016/05/gulp-with-ts.html

no, we totally can't add gulp as dependency

No that's not what i meant, i meant to look how gulp goes about allowing gulpfile.ts as good as ts-node is installed, they make it work, i thought maybe we can take their approach as example.

are you able to provide more specific implementation details?

Well when using gulp i can drop a gulpfile.ts instead, then use TS in it and as good as i have ts-node installed, gulp works flawlessly.

So i thought maybe having ts-node as a peer dependency and allow ts files directly wouldn't be that hard given gulp already does it.

ah noo I won't have ts-node as a dependency, need some better solution

Any specific reason not to?

Because it does not seem to be a good solution.

It looks like a good fit for me, alternative is to compile on demand, detecting file ext and compile with tsc if needed, but unless there's a good way to get the result on memory, it will have the same issue, the generated js will show up in folder structure, which could easily be fixed by using ts-node if available.

I dont think its a good solution. If there is no more simple solution I would like avoiding support for ts files out of the box. Who want to support ts files can run typeorm via ts-node by themself

Then again how would we run typeorm cli command with ts-node ourselves? idk how we can do that, and there's no docs about the subject, if cli can be called using ts-node, then it's as simple as using an npm script command to abstract that and problem solved, but idk how would we run the cli ourselves.

You can execute any node app using ts-node:

ts-node ./node_modules/.bin/typeorm

This way it will compile ts files on the fly.

This should be part of ts-node documentation, but yeah its good to mention about it in typeorm documentation too.

Thanks again. My question is resolved, so, I'm closing it. further discussion is welcome

Had same problem, solved by having:
"migrate": "ts-node ./node_modules/.bin/typeorm migrations:generate"
in the scripts section of package.json and then doing:
npm run migrate -- --name InitialMigration

HI everyone

I have the same problem, and if i'm following previous solutions to make typeorm migration command working, when i try this:
ts-node ./node_modules/.bin/typeorm migrations:generate -n testMigration

I got this error:

basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:588:28)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Function.Module.runMain (module.js:665:10)
    at Object.<anonymous> (C:\Projects\backend\node_modules\ts-node\src\_bin.ts:182:12)
    at Module._compile (module.js:624:30)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Versions:
+-- [email protected]
+-- types/[email protected],

If you have an answer, it's welcome!
Thx a lot!

It's seems it's due to windows.
I tried with typeorm.cmd instead of typeorm but nothing working well with ts-node like expected.

Got same error as @gmongin. Any workaround with ts-node?

Same error as @gmongin and @martinsura

@martinsura this worked for me.
Added script in package.json
"migrate": "ts-node ./node_modules/typeorm/cli.js migrations:generate"
Then generated migration like so...
yarn migrate -- --name BaseMigration

Guys to summarize, TypeORM uses TypeScript to enhance javascript and enable a better way of declaring your schema, however it doesn't give you TS to JS compilation nor a middleware for it's execution directly in TS, so when you execute TypeORM, you NEED to use ts-node by prepending it to all commands used in console (though it's easier to hard code such commands in npm scripts in package.json).

About @gmongin issue, the following line is a bash command, i doubt it would work in windows cmd or powershell, maybe try installing git-bash, babun (i like it, but some issues with yarn in the most recent version), or some other bash emulator:

basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

Lastly i know packages which accept TS files, like Gulp, they accept their config file to be made in TS, and they will tap into ts-node if installed, i asked before if that can be done here as well, but most people said it's not a priority, and prepending the TypeORM command with ts-node is a good enough workaround, what a shame, i feel that most newcomers bump into this and creates a high barrier of entry.

I agree. You need to use ts-node. The problem for me is both ./node_modules/.bin/typeorm and ./node_modules/.bin/typeorm.cmd fail to generate/run/revert the migrations. I can create an empty migration using typeorm migrations:create without any issues.

My work-around is accessing the typeorm cli.js directly using package json, like so...
"migrations:generate": "ts-node ./node_modules/typeorm/cli.js migrations:generate",
"migrations:run": "ts-node ./node_modules/typeorm/cli.js migrations:run",
"migrations:revert": "ts-node ./node_modules/typeorm/cli.js migrations:revert"
Then running the migrations like so...
yarn migrations:generate --name BaseMigration
yarn migrations:run
yarn migrations:revert
This is working for me on Windows10, using VSCode and git-bash terminal.
I am enjoying working with TypeORM, I like it.

@joebieb Are your migration generation working? if i understood correctly you can create empty ones, but not generate/run/revert, what kind of errors shows?

I have switched to my linux box for dev for some other reasons. I will try to reproduce the errors when I fire up my windows box again, hopefully this weekend.
I was getting the same error as above:
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^
Then a different one when explicitly executed the typeorm.cmd

using the cli directly solved my issue, so I moved on.

@joebieb If you have a linux box, have you tried and see if it works in linux? Just to make sure this is a windows only issue, or it happens in your project.

@luchillo17

Windows 10, VSCode, bash shell (cmd.exe - same error)

YARN

$ yarn migrations:run
yarn run v1.1.0
$ ts-node ./node_modules/.bin/typeorm migrations:run
C:\Repositories\FairServer\fairserver\node_modules\.bin\typeorm:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^

SyntaxError: missing ) after argument list
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at Object.<anonymous> (C:\Repositories\FairServer\fairserver\node_modules\ts-node\src\_bin.ts:182:12)
at Module._compile (module.js:624:30)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

NPM

$ npm run migrations:run

> [email protected] migrations:run C:\Repositories\FairServer\fairserver
> ts-node ./node_modules/.bin/typeorm migrations:run

C:\Repositories\FairServer\fairserver\node_modules\.bin\typeorm:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^

SyntaxError: missing ) after argument list
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at Object.<anonymous> (C:\Repositories\FairServer\fairserver\node_modules\ts-node\src\_bin.ts:182:12)
at Module._compile (module.js:624:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] migrations:run:ts-node ./node_modules/.bin/typeorm migrations:run `npm ERR! Exit status 1` `npm ERR!` `npm ERR! Failed at the [email protected] migrations:run script.` `npm ERR! This is probably not a problem with npm. There is likely additional logging output above.`
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\joe\AppData\Roaming\npm-cache\_logs\2017-11-04T01_25_40_756Z-debug.log

SPECIFYING typeorm.cmd

$ npm run migrations:run

> [email protected] migrations:run C:\Repositories\FairServer\fairserver
> ts-node ./node_modules/.bin/typeorm.cmd migrations:run

C:\Repositories\FairServer\fairserver\node_modules\.bin\typeorm.cmd:1
(function (exports, require, module, __filename, __dirname) { @IF EXIST "%~dp0\node.exe" (
^

SyntaxError: Invalid or unexpected token
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:588:28)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at Object.<anonymous> (C:\Repositories\FairServer\fairserver\node_modules\ts-node\src\_bin.ts:182:12)
at Module._compile (module.js:624:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] migrations:run:ts-node ./node_modules/.bin/typeorm.cmd migrations:run npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] migrations:run script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.`

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\joe\AppData\Roaming\npm-cache\_logs\2017-11-04T01_30_27_977Z-debug.log

@luchillo17

Ubuntu 17.04, VSCode, bash

No problems works fine. Same code.

Yeah, just what i expected, that code is indeed directed towards bash, so it makes sense it doesn't work in cmd.exe, now it would be a different story if you tell me that you tried Git-Bash or Cmder or Babun and it didn't worked there.

git-bash is my default terminal for VSCode in windows.

git-bash and cmd.exe produce same results on windows.

The Typeorm files in node_modules/.bin are different between windows and linux.

node_modules/.bin/typeorm - Windows

#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

caseunamein
*CYGWIN*) basedir=cygpath -w "$basedir";;
esac

if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../typeorm/cli.js" "$@"
ret=$?
else
node "$basedir/../typeorm/cli.js" "$@"
ret=$?
fi
exit $ret

node_modules/.bin/typeorm - Ubuntu

#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
var SchemaSyncCommand_1 = require("./commands/SchemaSyncCommand");
var SchemaDropCommand_1 = require("./commands/SchemaDropCommand");
var QueryCommand_1 = require("./commands/QueryCommand");
var EntityCreateCommand_1 = require("./commands/EntityCreateCommand");
var MigrationCreateCommand_1 = require("./commands/MigrationCreateCommand");
var MigrationRunCommand_1 = require("./commands/MigrationRunCommand");
var MigrationRevertCommand_1 = require("./commands/MigrationRevertCommand");
var SubscriberCreateCommand_1 = require("./commands/SubscriberCreateCommand");
var SchemaLogCommand_1 = require("./commands/SchemaLogCommand");
var MigrationGenerateCommand_1 = require("./commands/MigrationGenerateCommand");
var VersionCommand_1 = require("./commands/VersionCommand");
var InitCommand_1 = require("./commands/InitCommand");
var CacheClearCommand_1 = require("./commands/CacheClearCommand");
require("yargs")
.usage("Usage: $0 <command> [options]")
.command(new SchemaSyncCommand_1.SchemaSyncCommand())
.command(new SchemaLogCommand_1.SchemaLogCommand())
.command(new SchemaDropCommand_1.SchemaDropCommand())
.command(new QueryCommand_1.QueryCommand())
.command(new EntityCreateCommand_1.EntityCreateCommand())
.command(new SubscriberCreateCommand_1.SubscriberCreateCommand())
.command(new MigrationCreateCommand_1.MigrationCreateCommand())
.command(new MigrationGenerateCommand_1.MigrationGenerateCommand())
.command(new MigrationRunCommand_1.MigrationRunCommand())
.command(new MigrationRevertCommand_1.MigrationRevertCommand())
.command(new VersionCommand_1.VersionCommand())
.command(new CacheClearCommand_1.CacheClearCommand())
.command(new InitCommand_1.InitCommand())
.demand(1)
.alias("v", "version")
.help("h")
.alias("h", "help")
.argv;
require("yargonaut")
.style("blue")
.style("yellow", "required")
.helpStyle("green")
.errorsStyle("red");
` //# sourceMappingURL=cli.js.map`

To be honest i don't develop on windows, but the most suspicious line is this:

basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

I guess it tries to get the current dir, however i don't get the echo & sed commands with such parameters, that command also fails if run directly in my linux because echo"$0" returns -bash instead of any path at all, i would dare to say this line is malformed for windows.

If i recall correctly, that sed command should be doing some / replacements for \, as you may know, folder slashes are different in windows, so the damage is in the echo "$0" command, which doesn't return anything useful in linux, could you run it in windows to see what it gives?

Hi guys,
I use an approach from @joebieb, on VStudio Code and Powershell terminal (edit: on Windows 10).
I can create an empty migration file, but when I try to sync schema or generate a migration, I get the following:

No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migrations:create" command

Here are my settings from ormconfig.json
grafik

and I have two entities in the folder.
I am not sure if this is a problem with ts files, or is this something to do with configuration?

@MiroKov Most of the time that kind of log means your database is synced with the latest changes on the entities, which means those 2 entities you mention are already created && || updated in your DB.

@luchillo17
Thanks for the answer. Just created another entity just now, and it still wont generate migrations.
I also found in another thread #350 that the migrations work just with mysql (28 Jul 2017).
Not an expert in javascript :-), but based on what I saw in source code I would say that is still the case.

Interesting, i have migrations with PostgreSQL, maybe it's driver dependent, what kind of DB you're using?

I use Microsoft SQL.

Can't help much myself, i use PostgreSQL and works ok.

I see now that it is implemented, didn't look close enough.
You helped already :-). Now I know that the implementation is there.

I will google a bit to see how to debug this issue. I am new to this world of javascript/node.
If I manage to find something I will post it here.

@MiroKov I typically use Postgres as well. When I connect to MSSQL and try to generate a migration, I get the same error. The migration file is NOT created in my project but the tables DO get created in the database. Synchronize is off, so I'm not sure what is creating the tables. It seems like the tables are being created first, then when it tries to create the migration, there is nothing to do. I tried creating an empty migration and that worked. I added some code to the empty migration, ran the migration and the migration ran and updated the database.
It just seems like when you try to generate a migration for MSSQL a db sync is being run before the generate migrations.

For anyone else having issues using ts-node in yarn workspaces or lerna. Just make a file called tsnode-typeorm.js:

require('ts-node').register({ typeCheck: false });
require('typeorm/cli');

To run migrations run node tsnode-typeorm migrations:run

There's a way to generate a migration in Ionic?

Best Regards

@aluco100 migration generation is supported only in mysql right now, we are planning to release its support in sqlite in 0.2.0

Note that since babel now supports Typescript, if you are using babel-node, be sure to add .ts to the extensions argument.

I agree. You need to use ts-node. The problem for me is both ./node_modules/.bin/typeorm and ./node_modules/.bin/typeorm.cmd fail to generate/run/revert the migrations. I can create an empty migration using typeorm migrations:create without any issues.

My work-around is accessing the typeorm cli.js directly using package json, like so...
"migrations:generate": "ts-node ./node_modules/typeorm/cli.js migrations:generate",
"migrations:run": "ts-node ./node_modules/typeorm/cli.js migrations:run",
"migrations:revert": "ts-node ./node_modules/typeorm/cli.js migrations:revert"
Then running the migrations like so...
yarn migrations:generate --name BaseMigration
yarn migrations:run
yarn migrations:revert
This is working for me on Windows10, using VSCode and git-bash terminal.
I am enjoying working with TypeORM, I like it.

Just want to help others who also looked into this solution, now the migration commands are Singular, eg:
"migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate",

typeorm Version I am using: "~0.2.7"

If I use
"migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate"
in package.json I get the error message "missing argument n".

These scripts are working for me:

  "migration:generate": "ts-node ./node_modules/typeorm/cli.js migration:generate -n",

  "migration:run": "ts-node ./node_modules/typeorm/cli.js migration:run",

  "migration:revert": "ts-node ./node_modules/typeorm/cli.js migration:revert"

Then in commandline:
npm run migration:generate MigrationName

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

Was this page helpful?
0 / 5 - 0 ratings