How to specify ormconfig.ts for TypeORM?

58,878

Solution 1

At the time of writing, TypeORM only look for ormconfig.json and ignores ormconfig.ts. There is work in progress to support it though.

Beside having ormconfig.json you need these commands in your package.json.

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
"migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection  --name ",
"migration:run": "npm run typeorm -- migration:run"

Solution 2

Hey i up this conversation since i can propose you a solution.

You can put the following line in your package.json file:

"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/database.ts",

And your ts config must export directly the config by doing that:

export = { /* your config */ };

As you can see, you can also specify the path of your config. No need for your config to be at the root level of your project.

Hope that will help you

Solution 3

Just remove the default while exporting. Your ormconfig.ts should be something like:

import env from './src/env';

export = {
  host: env.DB_CONFIG.host,
  type: 'mysql',
  port: env.DB_CONFIG.port,
  username: env.DB_CONFIG.username,
  password: env.DB_CONFIG.password,
  database: env.DB_CONFIG.database,
  entities: [
    'src/**/**.entity{.ts,.js}',
  ],
  migrations: [
    'src/database/migrations/*.ts',
  ],
  cli: {
    migrationsDir: 'src/database/migrations',
  },
  synchronize: false,
};

In my case I'm using a main env.ts file, as the database connection needs to be different depending on the environment. Also, don't forget using ts-node for dealing with typeorm cli in package.json:

...
"scripts": {
    ...
    "migrate:create": "ts-node ./node_modules/typeorm/cli.js migration:create -n",
    "migrate:up": "ts-node ./node_modules/typeorm/cli.js migration:run",
    "migrate:down": "ts-node ./node_modules/typeorm/cli.js migration:revert"
    ...
  }
...

So creating, running or rolling back migrations should be like:

npm run migrate:create FileName
npm run migrate:up
npm run migrate:down

Solution 4

Project Structure

.
├── src // Typescript files
│   ├── entities
│   │   └── User.ts
│   ├── db
│   │   └── ormconfig.ts
│   │   ├── migrations
│   │   │   └── ... // migration files
├── tsconfig.json
├── package.json

Requirements

  • Typeorm should be able to use src/db/ormconfig.ts file for connection.
  • We should be able to create migrations, and perform all typeorm cli supported operations using src/db/ormconfig.ts file.

Possiblility

We might be able to accomplish this using ts-node package available for typescript.

Solution and Github Link

Please checkout https://github.com/devjayantmalik/sample-node-typeorm for complete example.

Contents of src/db/ormconfig.ts file are:

import path from "path";
import { ConnectionOptions } from "typeorm";

export default {
  name: "default",
  type: "better-sqlite3",
  database: ":memory:",
  synchronize: true,
  migrationsRun: true,
  dropSchema: false,
  entities: [path.join(__dirname, "..", "entities", "**", "*.*"), path.join(__dirname, "..", "entities", "*.*")],
  migrations: [path.join(__dirname, "migrations", "*.*")],
  cli: {
    entitiesDir: path.join(__dirname, "..", "entities"),
    migrationsDir: path.join(__dirname, "migrations")
  }
} as ConnectionOptions;

Script section of src/db/package.json file are:

"scripts": {
  "dev": "ts-node-dev src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js",
  "typeorm": "ts-node ./node_modules/.bin/typeorm -f ./src/db/ormconfig.ts",
  "migration:generate": "yarn run typeorm migration:generate -n",
  "migration:blank": "yarn run typeorm migration:create -n"
},```

## Usage

```bash
# Generate a blank migration
yarn migration:blank migration-name-here

# Generate migrations from database and entities.
yarn migration:generate

# Roll back a migration using cli options.
yarn typeorm migration:down

Solution 5

Solution

Specify ormconfig.ts

import { ConnectionOptions } from 'typeorm';

// Check typeORM documentation for more information.
const config: ConnectionOptions = {
    type: 'postgres',
    host: process.env.SQL_IP, // localhost
    port: process.env.SQL_PORT,// 5432
    username: process.env.SQL_USER, // databse login role username
    password: process.env.SQL_PASSWORD, // database login role password
    database: process.env.SQL_DATABASE, // db name

    // entities name should be **.entity.ts
    entities: [__dirname + '/**/*.entity{.ts,.js}'],

    // We are using migrations, synchronize should be set to false.
    // synchronize: process.env.TYPEORM_SYNCHRONIZE
    //  ? process.env.TYPEORM_SYNCHRONIZE.toLowerCase() === 'true'
    //  : false,
    synchronize: false,

    // Run migrations automatically,
    // you can disable this if you prefer running migration manually.
    migrationsRun: false,

    logging: false,
    // logger: 'advanced-console',

    // Allow both start:prod and start:dev to use migrations
    // __dirname is either dist or src folder, meaning either
    // the compiled js in prod or the ts in dev.
    migrations: [__dirname + '/migrations/*{.ts,.js}'],
    cli: {
        // Location of migration should be inside src folder
        // to be compiled into dist/ folder.
        migrationsDir: 'src/database/migrations'
    }
};

export = config;


In Package.json define this under scripts

"typeorm": "ts-node --files -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/database/config.ts"
"db:migrate": "npm run typeorm migration:run",
"db:create-migration": "npm run typeorm migration:create -- -n",
Share:
58,878

Related videos on Youtube

Hussain Ali Akbar
Author by

Hussain Ali Akbar

I am a Software Developer focusing on server-side development. I am always keen on learning new items that help me grow professionally as a software Developer.

Updated on January 18, 2022

Comments

  • Hussain Ali Akbar
    Hussain Ali Akbar over 2 years

    I have created a sample TypeORM project using the TypeORM CLI which has ormconfig.json by default:

    {
       "type": "postgres",
       "host": "localhost",
       "port": 5432,
       "username": "postgres",
       "password": "postgres",
       "database": "test",
       "synchronize": false,
       "entities": [
          "src/entity/**/*.ts"
       ],
       "migrations": [
          "database/migrations/**/*.ts"
       ],
       "subscribers": [
          "src/subscriber/**/*.ts"
       ],
       "cli": {
          "entitiesDir": "src/entity",
          "migrationsDir": "database/migrations",
          "subscribersDir": "src/subscriber"
       }
    }
    

    this is the directory structure:

    -database
      -migrations
    -src
      -entity
    -ormconfig.json
    

    This creates the migrations in the database/migrations folder properly as well as executes the migrations from it.

    I replaced ormconfig.json with the following ormconfig.ts :

    export default {
        type: 'postgres',
        host: 'localhost',
        port: 5432,
        username: 'postgres',
        password: 'postgres',
        database: 'test',
        synchronize: false,
        "entities": [
            "src/entity/**/*.ts"
        ],
        "migrations": [
             "database/migrations/**/*.ts"
        ],
        "subscribers": [
            "src/subscriber/**/*.ts"
        ],
        "cli": {
            "entitiesDir": "src/entity",
            "migrationsDir": "database/migrations",
            "subscribersDir": "src/subscriber"
        }
    };
    

    This however creates migrations in the root directory instead of inside database/migrations.

    Can anyone help me in figuring out what's missing here and how I can use ormconfig.ts to generate migrations inside the intended directory?

    • aRtoo
      aRtoo over 4 years
      I have an issue with this now. have you fixed this?
  • Developer Dave
    Developer Dave over 2 years
    Since the typeorm package has its bin mapped already to cli.js you can omit the cli.js in those commands. So it's just ts-node ./node_modules/typeorm ...
  • Aseer KT Miqdad
    Aseer KT Miqdad over 2 years
    Do you have working repo for the example you provided?.
  • Jayant Malik
    Jayant Malik over 2 years
    Sorry, I don't have one exposed as public.
  • dfsg76
    dfsg76 over 2 years
    could you please please add a minimal working example repo?
  • Jayant Malik
    Jayant Malik over 2 years
    Check github link in Solutions section. I have updated the answer to include github link.
  • Dživo Jelić
    Dživo Jelić about 2 years
    Can you put you .env file here it would help Thank you.