I was getting the following error with the Nodemailer package in a Cloudflare Worker and wanted to document what I found.

Module not found: Error: Can't resolve 'child_process' in '~/node_modules/nodemailer/lib/sendmail-transport'
1

There are 1 answers

0
Samuel Earl On

While developing with Cloudflare Workers, I was getting the following error with the Nodemailer package:

Module not found: Error: Can't resolve 'child_process' in '~/node_modules/nodemailer/lib/sendmail-transport'

When I researched the error, I found that Webpack is trying to bundle things for the client that can only be used in the server. See https://github.com/webpack/webpack/issues/744.

One possible solution was to add the externals property to a custom webpack.config.js file for my Worker and include all the modules that cannot be resolved by Webpack. See https://github.com/webpack/webpack/issues/744#issuecomment-320437402.

So my webpack.config.js file would look like this:

module.exports = {
  target: "webworker",
  entry: "./index.js",
  externals: [
    "child_process",
    "dns",
    "fs",
    "net",
    "tls",
  ]
}

However, I found out that you can't use packages like Nodemailer in a Cloudflare Worker. Cloudflare Workers do not have a Node environment, so you can't use Node packages like you would in a server-side platform that has a Node environment. So the Webpack configurations above won't do you much good anyway because you still can't use Nodemailer to send email from a Cloudflare Worker. However, there are often alternative ways to use Node packages or other Node features in a Cloudflare Worker. For example, in order to send email from a Worker you have to use a REST API instead of a Node package: