Error importing handlebars: Error [ERR_REQUIRE_ESM]: require() of ES Module

I am trying to implement a nestjs server using typescript to send customized emails with embedded html templates,i am using nodemailer-handlebar dependency but when i run the code it consoles following error. **[Nest] 32560 - 30/01/2025, 10:32:49 am LOG [NestFactory] Starting Nest application... Error importing handlebars: Error [ERR_REQUIRE_ESM]: require() of ES Module ** Since typescript is first compiled in Javascript then executed. error is originating form compiled JS in directory dist/src/email.service.js.

Moreover, application runs but sends blank emails, which means templates aren't being executed correctly,

Thank you in Advance!

Below is the implementation of email.service.ts

import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import { join } from 'path';
// import welcome from '../../templates/welcome.hbs'

@Injectable()
export class EmailService {
  private transporter: nodemailer.Transporter;

  constructor() {
    this.transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });

    import('nodemailer-express-handlebars')
      .then((hbs) => {
        this.transporter.use(
          'compile',
          hbs.default({
            viewEngine: {
              extname: '.hbs',
              layoutsDir: join(__dirname, '../../', 'templates'),
              defaultLayout: false,
            },
            viewPath: join(__dirname, '../../', 'templates'),
            extName: '.hbs',
          }),
        );
      })
      .catch((err) => {
        console.error('Error importing handlebars:', err);
      });
  }

  async sendEmail(to: string, subject: string, template: string, context: any) {
    const mailOptions = {
      from: process.env.EMAIL_USER,
      to,
      subject,
      // html: template,
      template,
      context, 
    };

    await this.transporter.sendMail(mailOptions);
  }
}

below is the email.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { EmailService } from './email.service';

@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  @Post('send')
  async sendEmail(@Body() body: { email: string; name: string }) {
    const { email, name } = body;
    await this.emailService.sendEmail(email, 'Welcome to Our App!', 'welcome', { name, email });
    return { message: 'Email sent successfully!' };
  }
}

i have placed templates folder in the root directory outside src folder as welcome.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome Email</title>
</head>
<body>
    <h2>Hello, {{name}}!</h2>
    <p>Welcome to our platform. We’re excited to have you on board!</p>
    <p>Your registered email is: <strong>{{email}}</strong></p>
    <p>Best regards, <br> The Team</p>
</body>
</html>

But when i run the application, it compiles it in JS and imports nodemiler as

Upvotes: 1

Views: 32

Answers (0)

Related Questions