NestJS conditional module import

Viewed 1325

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

2 Answers

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,
  ],
})

here's a small snippet that does importing within a code construct (dynamic importing, like how require's would allow):

        const events = files.filter(file => file.endsWith('.mjs'));
        for (const file of events) {
            import(`${eventDir}${file}`)
                .then(function({ default: event }) {
                    const eventName = file.split('.')[0];
                    dBot.on(eventName, event.bind(null, dBot));
                    console.log(`${success} Loaded event ${eventName}`);
                })
                .catch(function(err) {
                    console.error(`${error}: Error loading event: ${err}`);
                    return;
                });

I think this gets you what you want, just put the conditions around it as needed, instead of my for loop, use an if statement, or whatever.

Related