【问题标题】:How to specify ormconfig.ts for TypeORM?如何为 TypeORM 指定 ormconfig.ts?
【发布时间】:2019-02-10 17:29:41
【问题描述】:

我使用默认具有 ormconfig.json 的 TypeORM CLI 创建了一个示例 TypeORM 项目:

{
   "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"
   }
}

这是目录结构:

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

这会在 database/migrations 文件夹中正确创建迁移,并从中执行迁移。

我将 ormconfig.json 替换为以下 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"
    }
};

然而,这会在根目录而不是在 database/migrations 中创建迁移。

谁能帮我弄清楚这里缺少什么以及如何使用 ormconfig.ts 在预期目录中生成迁移?

【问题讨论】:

  • 我现在遇到了这个问题。你修好了吗?

标签: javascript node.js typescript typeorm


【解决方案1】:

嘿,我可以讨论这个话题,因为我可以给你一个解决方案。

您可以在package.json 文件中加入以下行:

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

并且您的 ts 配置必须通过这样做直接导出配置:

export = { /* your config */ };

如您所见,您还可以指定配置的路径。您的配置无需位于项目的根级别。

希望对你有帮助

【讨论】:

    【解决方案2】:

    在撰写本文时,TypeORM 仅查找 ormconfig.json 而忽略 ormconfig.ts。不过有work in progress 支持。

    除了 ormconfig.json 之外,您还需要在 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"
    

    【讨论】:

      【解决方案3】:

      导出时只需删除default。 你的ormconfig.ts 应该是这样的:

      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,
      };
      

      在我的例子中,我使用了一个主要的env.ts 文件,因为数据库连接需要根据环境而有所不同。 另外,不要忘记在package.json 中使用ts-node 处理typeorm cli

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

      所以创建、运行或回滚迁移应该是这样的:

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

      【讨论】:

      • 由于typeorm 包的bin 已经映射到cli.js,您可以在这些命令中省略cli.js。所以它只是ts-node ./node_modules/typeorm ...
      【解决方案4】:

      项目结构

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

      要求

      • Typeorm 应该可以使用src/db/ormconfig.ts 文件进行连接。
      • 我们应该能够创建migrations,并使用src/db/ormconfig.ts 文件执行所有typeorm cli 支持的操作。

      可能性

      我们或许可以使用可用于 typescript 的 ts-node 包来完成此操作。

      解决方案和 Github 链接

      完整示例请查看https://github.com/devjayantmalik/sample-node-typeorm

      src/db/ormconfig.ts 文件的内容是:

      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;
      

      src/db/package.json 文件的脚本部分是:

      "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
      

      【讨论】:

      • 你提供的例子有工作回购吗?
      • 抱歉,我没有公开的。
      • 能否请您添加一个最小的工作示例 repo?
      • 查看解决方案部分的 github 链接。我已经更新了答案以包含 github 链接。
      【解决方案5】:

      解决方案

      指定 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;
      
      
      

      在 Package.json 中的脚本下定义这个

      "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",
      

      【讨论】:

        【解决方案6】:

        如果您使用带有 PnP 的 Yarn 2 作为包管理器,那么您不能在此处与其他解决方案完全相同,因为您没有 node_modules 目录。

        这是我如何让它工作的方法:

        package.json

        {
          "scripts": {
            "typeorm": "yarn node -r ts-node/register/transpile-only $(yarn bin typeorm)",
            "generate-migration": "yarn typeorm --config ormconfig.ts migration:generate --check",
          }
          "dependencies": {
             "typeorm": "^0.2.41",
          }
          "devDependencies": {
            "ts-node": "^10.4.0",
          }
        }
        

        ormconfig.ts

        /* eslint-disable no-process-env */
        import dotenv from 'dotenv';
        import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
        
        dotenv.config();
        dotenv.config({ path: './.env.local' });
        
        export = {
          type: 'postgres',
          host: process.env.DB_HOST,
          port: process.env.DB_PORT,
          username: process.env.DB_USERNAME,
          password: process.env.DB_PASSWORD,
          database: process.env.DB_NAME,
          entities: ['src/infrastructure/persistence/**/*.entity.ts'],
          migrations: ['src/infrastructure/persistence/migrations/**/*.{ts,js}'],
          cli: {
            migrationsDir: 'src/infrastructure/persistence/migrations',
          },
          namingStrategy: new SnakeNamingStrategy(),
        };
        

        【讨论】:

          【解决方案7】:

          花了一些时间,但这让它对我有用 - build 将 TS 代码编译为 dist 文件和 node 来运行它。 ts-node 不想与我的项目配合得很好,我认为这很干净。 nodemon 用于在 dev 中运行它 - 虽然我认为我需要为那个 / 添加 ts-node 仍然可以编译和运行。

          ormconfig.ts

          import { ConnectionOptions } from 'typeorm';    
          export const baseConfig: ConnectionOptions = {
                synchronize: true, // TODO turn false after initial setup i.e. when moving to migrations
                type: 'mysql',
                host: 'localhost',
                port: 3306,
                username: 'xxx',
                password: 'xxx',
                database: 'xxx',
                entities: ['dist/Entities/**/**.entity.js'],
                migrations: ['dist/Migrations/*.js'],
                cli: {
                  entitiesDir: 'dist/Entities/**/*.js',
                  migrationsDir: 'dist/Migrations/*.js'
                }
              };
          

          和 package.json 脚本

            "scripts": {
              "build": "rimraf ./dist && tsc",
              "start": "npm run build && node dist/index.js",
              "dev": "nodemon src/index.ts",
              "format:prettier": "prettier --config .prettierrc 'src/**/*.ts' --write",
              "lint": "eslint . --ext .ts",
              "lint:fix": "eslint . --ext .ts --fix",
              "test": "jest --runInBand"
            },
          

          【讨论】:

            猜你喜欢
            • 2022-07-25
            • 1970-01-01
            • 1970-01-01
            • 2022-07-07
            • 2019-03-26
            • 2019-06-03
            • 1970-01-01
            • 2021-04-03
            • 2019-12-25
            相关资源
            最近更新 更多