Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ERR_REQUIRE_ESM]: require() of ES Module when importing nodemailer-express-handlebars #76

Open
khaleb-dev opened this issue Dec 6, 2024 · 3 comments

Comments

@khaleb-dev
Copy link

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/khali/js_workspace/heim/node_modules/nodemailer-express-handlebars/index.js from /home/khali/js_workspace/heim/src/services/mailer.ts not supported.
Instead change the require of index.js in /home/khali/js_workspace/heim/src/services/mailer.ts to a dynamic import() which is available in all CommonJS modules.
I am getting the above error when I import the package as see below in my code:
import path from 'path';
import { createTransport } from 'nodemailer';
import { Readable } from 'nodemailer/lib/xoauth2';
import { AttachmentLike } from 'nodemailer/lib/mailer';
import config from '../config';
import { logger } from '../utils';
import hbs from 'nodemailer-express-handlebars';

const { app, mail } = config;

class NodeMailerAdapter {
  private static hbsConfig = {
    viewEngine: {
      extName: '.hbs',
      partialsDir: path.join(__dirname, '../mail-templates'),
      layoutsDir: path.join(__dirname, '../mail-templates/'),
      defaultLayout: '',
    },
    viewPath: path.join(__dirname, '../mail-templates/'),
    extName: '.hbs',
  };

  private static transporter = createTransport({
    port: Number(mail.port),
    host: mail.host,
    auth: {
      user: mail.user,
      pass: mail.pass,
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  public static async sendEmail<T>({
    to,
    subject,
    text,
    html,
    context,
  }: {
    to: string | Array<string>;
    subject: string;
    text?: string;
    html: string | Buffer | Readable | AttachmentLike | undefined;
    context: T;
  }) {
    NodeMailerAdapter.transporter.use(
      'compile',
      hbs(NodeMailerAdapter.hbsConfig),
    );
    const mailData = {
      from: `${app.name} <${mail.user}>`,
      to,
      subject,
      text,
      template: html,
      context: {
        ...context,
        app_name: app.name,
        support_mail: mail.support,
        year: new Date().getFullYear(),
      },
    };

    const infoMail = await NodeMailerAdapter.transporter.sendMail(mailData);
    logger.info('mail sent');
    logger.info(infoMail);
  }
}

I have tried to dynamically import the module at runtime like this:
const hbs = (await import('nodemailer-express-handlebars')).default;
and like this:
const { default: hbs } = await import('nodemailer-express-handlebars');
but still didn't work.

Here is my package.json if needed:

{
  "name": "heim-backend",
  "version": "1.0.0",
  "description": "Backend service",
  "main": "src/app.ts",
  "license": "MIT",
  "scripts": {
    "dev": "nodemon --exec ts-node src/app.ts",
    "compile": "./node_modules/.bin/tsc --project ./tsconfig.json",
    "serve": "node build/app.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.19.2",
    "express-handlebars": "^8.0.1",
    "jsonwebtoken": "^9.0.2",
    "morgan": "^1.10.0",
    "nodemailer": "^6.9.15",
    "nodemailer-express-handlebars": "^7.0.0",
    "pg": "^8.12.0",
    "typeorm": "^0.3.20",
    "winston": "^3.13.0",
    "winston-daily-rotate-file": "^5.0.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^4.17.21",
    "@types/express-fileupload": "^1.5.0",
    "@types/jsonwebtoken": "^9.0.6",
    "@types/morgan": "^1.9.9",
    "@types/node": "^20.14.10",
    "@types/nodemailer": "^6.4.16",
    "@types/nodemailer-express-handlebars": "^4.0.5",
    "nodemon": "^3.1.4",
    "ts-node": "^10.9.2",
    "typescript": "^5.5.3"
  }
}

And my tsconfig.json

{
    "compilerOptions": {
      "target": "es2016",
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true,
      "module": "CommonJS",
      "rootDir": "./src/",
      "moduleResolution": "node",
      "baseUrl": "./src",
      "resolveJsonModule": true,
      "outDir": "./build/",
      "removeComments": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "skipLibCheck": true
    },
    "exclude": ["node_modules"]
  }
@phsousadev
Copy link

I'm also going through the same problem

@kaskatiyski
Copy link

I downgraded to ^6.1.2 and I am not getting the error anymore.

@khaleb-dev
Copy link
Author

@kaskatiyski you did?
I am using ^7.0.0 at the moment. I'll downgrade as you did. I hope it'll work for me too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants