乐闻世界logo
搜索文章和话题

How to specify ormconfig.ts for TypeORM?

1个答案

1

In TypeORM, specifying a specific ormconfig.ts file is typically done by setting environment variables or directly providing a configuration object in the code during application startup.

Using Environment Variables

You can specify the path to the configuration file by setting the TYPEORM_CONFIG environment variable. For example, in the command line, set the environment variable before launching the application:

bash
export TYPEORM_CONFIG=/path/to/your/ormconfig.ts node your-app.js

Alternatively, on Windows, use the set command:

bash
set TYPEORM_CONFIG=/path/to/your/ormconfig.ts node your-app.js

Additionally, you can set the environment variable directly in the scripts section of package.json, ensuring the corresponding configuration file is used when running npm scripts.

json
"scripts": { "start": "TYPEORM_CONFIG=/path/to/your/ormconfig.ts ts-node src/index.ts" }

Specifying in Code

You can also directly provide a configuration object in the code rather than using an external configuration file. For example:

typescript
import { createConnection } from 'typeorm'; import { User } from './entity/User'; createConnection({ type: 'postgres', host: 'localhost', port: 5432, username: 'test', password: 'test', database: 'test', entities: [User], synchronize: true, logging: false }).then(connection => { // Here you can use the connection object }).catch(error => console.log(error));

In this case, you directly provide the database connection and other ORM settings in the code, without needing an external ormconfig.ts file.

Using CLI

If you are using the TypeORM CLI, you can specify the configuration file location using the --config parameter:

bash
typeorm migration:run --config /path/to/your/ormconfig.ts

Summary

By default, TypeORM searches for configuration files like ormconfig.json, ormconfig.js, ormconfig.yml, ormconfig.xml, ormconfig.env, or ormconfig.toml in the project root directory. However, you can specify a particular configuration file or configure directly in the code using the methods described above.

Please note that TypeORM's configuration management may evolve with version updates; therefore, it is recommended to refer to the latest official documentation for accurate guidance.

2024年6月29日 12:07 回复

你的答案