AWS Lambda中使用MJML的Node.js函数报错:Cannot read property '1' of undefined
From your error stack trace, the issue clearly originates during the module import phase—before your sendEmail function even runs. The root cause is that a dependency chain (MJML → html-minifier → uglify-js) is trying to use the fs module to read files, but your webpack-packaged code is breaking this file system logic in the Lambda environment. Here's how to fix it:
Possible Solutions
1. Fix Webpack Configuration to Handle Node.js Modules
Webpack is likely modifying the file system-related code in uglify-js which wasn't designed to be bundled. Adjust your webpack config to mitigate this:
- Mock the
fsmodule (since you're passing MJML as a string directly, you don't need actual file system access):// webpack.config.js module.exports = { // ... your existing config node: { fs: 'empty' } }; - Prevent webpack from bundling MJML core modules (keep them as native Node.js imports):
module.exports = { // ... your existing config externals: { mjml: 'mjml', 'mjml-core': 'mjml-core' } };
2. Skip Webpack Entirely
Webpack isn't always necessary for Lambda functions. Try deploying your code without bundling:
- Run
npm install mjmllocally to install dependencies - Zip your function code,
package.json, and the entirenode_modulesfolder - Upload this zip directly to AWS Lambda
This lets MJML run in its native Node.js environment without webpack modifying its internal dependencies.
3. Adjust Dependency Versions
Some versions of MJML, html-minifier, or uglify-js have compatibility issues with Lambda's constrained environment:
- Downgrade to a well-tested MJML version like
4.13.0:npm install mjml@4.13.0 - Or upgrade to the latest MJML release to see if the file system handling bug has been patched.
4. Match Node.js Versions
Ensure your Lambda function uses the same Node.js version as your local development environment. Version mismatches can cause unexpected module loading errors—for example, if you develop on Node.js 18.x, set your Lambda runtime to Node.js 18.x.
After applying one of these fixes, redeploy your Lambda and test the function. You should see your sendEmail reached log and get the converted HTML output if successful.
内容的提问来源于stack exchange,提问作者Markussen

