根据环境使用不同的ormconfig.json文件

时间:2018-06-27 04:47:12

标签: node.js typescript typeorm

我的ormconfig.json当然是静态的,它看起来像:

{
   "type": "mariadb",
   "host": "localhost",
   "port": 3306,
   "username": "root",
   "password": "moove",
   "database": "moove_db",
   "synchronize": true,
   "logging": false,
   "entities": [
      "dist/entity/**/*.js"
   ],
   "migrations": [
      "dist/migration/**/*.js"
   ],
   "subscribers": [
      "dist/subscriber/**/*.js"
   ],
   "cli": {
      "entitiesDir": "dist/entity",
      "migrationsDir": "dist/migration",
      "subscribersDir": "dist/subscriber"
   }
}

但是如果我想为生产服务器创建另一个配置怎么办? 我是否要创建另一个配置文件?如何将typeorm指向其他配置文件?

2 个答案:

答案 0 :(得分:5)

目前,我能够将ormconfig.json更改为ormconfig.js,然后使用env变量,如下所示:

module.exports = {
   "port": process.env.port,
   "entities": [
      // ...
   ],
   "migrations": [
      // ...
   ],
   "subscribers": [
     // ...
   ],
   "cli": {
      // ...
   }
}

答案 1 :(得分:1)

请勿使用ormconfig.json。您可以像

一样直接将配置对象传递给createConnection()
import { createConnection } from "typeorm";

const config:any = {
       "port": process.env.port || "28017",
       "entities": [
          // ...
       ],
       "migrations": [
          // ...
       ],
       "subscribers": [
         // ...
       ],
       "cli": {
          // ...
       }
    }
    createConnection(config).then(async connection => {
        await loadPosts(connection);
    }).catch(error => console.log(error));