运行构建项目时无法在模块外部使用import语句错误

时间:2020-01-29 10:54:49

标签: angular postgresql typescript nestjs typeorm

问题已解决-见下文

我正在使用Angular,NestJS,TypeORM和PostgreSQL构建应用程序。我遇到的问题是,当我使用“ npm run start:dev”或“ npm run start”运行服务器时,服务器启动,但是当我转到“ dist”文件夹并尝试运行“ node main.js”时,服务器引发以下错误“ SyntaxError:无法在模块外部使用import语句” 。我需要这样做是因为我试图在Digitalocean上部署该应用程序并使用pm2。

以下是我的代码示例:

package.json:

    "start": "ts-node -r tsconfig-paths/register src/main.ts",
    "start:dev": "tsc-watch -p tsconfig.build.json --onSuccess \"node dist/src/main.js\"",
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./ormconfig.ts",
    "typeorm:migrate": "npm run typeorm migration:generate -- -n",
    "typeorm:run": "npm run typeorm migration:run",

ormconfig.ts

import * as yn from 'yn';
const config: any = {
type: process.env.DB_TYPE as any,
host: +process.env.DB_HOST,
port: +process.env.DB_PORT,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
ssl: yn(process.env.SSL_STATUS),
dialectOptions: {
    ssl: { require: yn(process.env.SSL_STATUS) },
  },
entities: [__dirname + '/**/*.entity{.ts,.js}'],

  synchronize: false,
  migrationsRun: true,
  migrations: ['src/database/migrations/**/*.ts'],
  cli: {
    migrationsDir: 'src/database/migrations',
  },
};

export = config;

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({isGlobal: true}),
    DatabaseModule,
    <other modules>
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

database.module.ts

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: configService.get('DB_TYPE'),
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USER'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_NAME'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: false,
      }),
    }),
  ],
  exports: [],
})
export class DatabaseModule {}

错误

enter image description here

谢谢您的帮助! :)

解决方案

问题是我在ormconfig.ts中使用了“ src”文件夹之外的“ import”语句。我将ormconfig.ts移至“数据库”文件夹,并解决了此问题。但是,无论何时我与数据库建立连接,我都必须提供ormconfig。例如在种子文件中:

const connection = await createConnection(config);

Source

0 个答案:

没有答案