Use handlebars template in nest js application

Viewed 896

I want to use handle bars template in my nest js application:

<!--confirmation.hbs-->
<p>Hello template</p>

This file is located in src/mail/templates/confirmation.hbs. Also i try to send this template as email:

//mail service
@Injectable()
export class EmailService {
  constructor(private readonly mailerService: MailerService) {}

  public example(): void {
    this.mailerService
      .sendMail({
        to: 'mail', // list of receivers
        from: 'test@nestjs.com', // sender address
        subject: 'Testing Nest MailerModule ✔', // Subject line
        template: './confirmation', 
      })
      .then((r) => {
        console.log(r, 'email is sent');
      })
      .catch((e) => {
        console.log(e, 'error sending email');
      });
  }
}

My app.module.ts looks:

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        service: 'Gmail',
        auth: {
          user: '---secret',
          pass: '---secret',
        },
      },
      defaults: {
        from: '"No Reply" <no-reply@localhost>',
      },
      template: {
        dir: __dirname + '/templates',
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    }),
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5433,
      username: '-',
      password: '-',
      database: '-',
      entities: [RegisterEntity],
      synchronize: true,
    }),
    AuthenticationModule,
  ],
  controllers: [AppController, AuthenticationController],
  providers: [AppService, AuthenticationService],
})

This is my main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix(CONSTANTS.GLOBAL_PREFIX);
  await app.listen(3000);
}
bootstrap();
This is my nest-cli.hbs

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      "mail/templates/**/*.hbs"
    ],
    "watchAssets": true
  }
}

The email is sent if don't send a template, so the code is working. Trying to send an email template like is my code above i get this error: TypeError: Cannot destructure property 'templateName' of 'precompile(...)' as it is undefined.
Question: Why i get this issue and how to get rid of it?

2 Answers

Your files are located inside src/mail/templates/.

But in your module you have dir: __dirname + '/templates',.

Here __dirname returns app.module.ts folder location path which is src/.

change

dir: __dirname + '/templates',

to

dir: __dirname + '/mail/templates',

Since this bug is not yet released #743 (to this date), I rolled back to previous version:

npm i --save @nestjs-modules/mailer@1.6.0 --force
Related