Node.js中ejs renderFile渲染模板时关联CSS文件样式不生效问题
问题原因
- 你代码中定义的CSS路径变量
options没有传入ejs.renderFile方法,EJS渲染时无法读取关联的样式文件 - 外部
<link>引用的CSS在nodeHtmlToImage生成图片时无法识别相对路径,会出现资源加载失败的情况 - 邮件场景下外部CSS本身兼容性极差,基本都会被邮箱服务商拦截
解决步骤
- 优先使用内联样式,将Bootstrap和自定义CSS的内容直接注入到EJS模板中,避免外部资源加载问题
- 修正路径拼接逻辑,使用
path.join适配多操作系统路径规则 - 给
nodeHtmlToImage添加加载等待配置,确保样式渲染完成后再生成图片
修正后代码示例
const fs = require('fs'); const path = require('path'); const ejs = require('ejs'); const nodeHtmlToImage = require('node-html-to-image'); function sendBusinessQuotaEmail() { const templatePath = path.join(process.cwd(), "/emailTemplates/businessQuotaEmailTemplate/businessQuotaEmailTemplate.ejs"); // 读取bootstrap和自定义CSS文件内容 const bootstrapCss = fs.readFileSync(path.join(process.cwd(), "你存放bootstrap.min.css的实际路径"), 'utf8'); const customCss = fs.readFileSync(path.join(process.cwd(), "/emailTemplates/businessQuotaEmailTemplate/businessQuotaEmailTemplate.css"), 'utf8'); // 将CSS内容传入模板数据 const templateData = { abc: 'test', bootstrapCss: bootstrapCss, customCss: customCss }; console.log('here sendBusinessQuotaEmail'); ejs.renderFile(templatePath, templateData, (err, html) => { if (err) { console.log('ejs render file error on line # 7209', err); return; } console.log('html', html); nodeHtmlToImage({ output: path.join(process.cwd(), "/tempFiles/download/abc.jpg"), html: html, waitUntil: 'load' // 等待所有资源渲染完成再截图 }).then(() => { console.log('The image was created successfully!'); }); }); }
EJS模板修改
在你的EJS模板<head>标签内添加如下代码,注入样式内容:
<head> <style> <%- bootstrapCss %> <%- customCss %> </style> </head>
注意必须使用<%-语法,不要用<%=,避免CSS特殊字符被转义导致样式失效
内容的提问来源于stack exchange,提问作者Ahmer Khan
相关产品推荐
相关产品推荐

