Is there a way to import a module conditionally? I want to check if the .env file exists, so I configure the env variables using the ConfigModule.
imports: [
UsersModule,
ConfigModule.forRoot({ load: [configuration] }), //I want to use this just if the .env file exists
MongooseModule.forRoot(
`mongodb+srv://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_URL}`,
),
],
Why: I deployed an api and configured the environment variables using heroku, and in production it works, but I dont have this variables to run the code in development, and I can't expose the .env in my public repository because this contains my database credentials. Because of this, I thinked to create a .env file and put it on .gitignore to don't publish with this file
You can do this pretty easily with a spread and a ternary check on whatever condition you want. Just return an empty array in the case that the check evaluates to false and the module will not be included.
@Module({
imports: [
...(isEnvPresent ? [ConfigModule.forRoot({ load: [configuration] })] : []),
UsersModule,
],
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With