使用ES6 import引入SendGrid Mail时出现变量未定义问题
解决SendGrid ES6 import引入后变量未定义问题
问题场景
使用require引入SendGrid的代码可正常运行:
const sgMail = require('@sendgrid/mail'); sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'test@example.com', from: 'test@example.com', subject: 'Sending with Twilio SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', html: '<strong>and easy to do anywhere, even with Node.js</strong>', }; sgMail.send(msg);
改用ES6的import语法后,运行报错sgMail变量未定义,调用setApiKey和send时均提示变量不存在:
import sgMail from '@sendgrid/mail'); // 此处存在语法错误 sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'test@example.com', from: 'test@example.com', subject: 'Sending with Twilio SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', html: '<strong>and easy to do anywhere, even with Node.js</strong>', }; sgMail.send(msg);
解决步骤
修正语法错误
原import语句末尾多了一个多余的右括号,正确写法为:import sgMail from '@sendgrid/mail';确保项目支持ES模块
在项目根目录的package.json中添加"type": "module"字段,让Node.js将.js文件识别为ES模块:{ "type": "module" }若不想修改
package.json,可将文件后缀改为.mjs。调整导入方式(若上述步骤无效)
部分版本的@sendgrid/mail可能使用命名导出而非默认导出,此时需改用整体导入:import * as sgMail from '@sendgrid/mail';
修正后的完整代码
import * as sgMail from '@sendgrid/mail'; sgMail.setApiKey(process.env.SENDGRID_API_KEY); const msg = { to: 'test@example.com', from: 'test@example.com', subject: 'Sending with Twilio SendGrid is Fun', text: 'and easy to do anywhere, even with Node.js', html: '<strong>and easy to do anywhere, even with Node.js</strong>', }; sgMail.send(msg);
内容的提问来源于stack exchange,提问作者Manas telavane
相关产品推荐
相关产品推荐

