You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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);

解决步骤

  1. 修正语法错误
    原import语句末尾多了一个多余的右括号,正确写法为:

    import sgMail from '@sendgrid/mail';
    
  2. 确保项目支持ES模块
    在项目根目录的package.json中添加"type": "module"字段,让Node.js将.js文件识别为ES模块:

    {
      "type": "module"
    }
    

    若不想修改package.json,可将文件后缀改为.mjs。

  3. 调整导入方式(若上述步骤无效)
    部分版本的@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:47:04