Svelte Node Adapter使用@sendgrid/mail构建时报错:sg.setApiKey不是函数
问题解决:Svelte Node Adapter构建后@sendgrid/mail调用setApiKey报错
问题原因
dev环境下Vite对ES模块的处理较为宽松,而构建产物适配Node的打包逻辑会改变@sendgrid/mail的模块导出结构,导致import * as sg获取的对象和dev环境不一致,setApiKey方法不再位于顶层对象,而是嵌套在default属性中。
解决方案
方案1:改用默认导入
修改导入语句为默认导入,直接拿到模块的核心导出对象:
import sg from "@sendgrid/mail"; export function SendMail(mailData: MailDataFormat) { sg.setApiKey("secret_from_env"); // 后续邮件发送逻辑 }
方案2:排除外部依赖打包
如果要保留命名导入,可以在Svelte配置中将@sendgrid/mail标记为外部依赖,让Node运行时直接加载原生模块,避免打包转换导致的结构变化:
修改svelte.config.js:
import adapter from '@sveltejs/adapter-node'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: vitePreprocess(), kit: { adapter: adapter(), // 将@sendgrid/mail排除在打包流程外 serverDependenciesToExternalize: ['@sendgrid/mail'] } }; export default config;
额外提示
建议使用SvelteKit的环境变量方案加载敏感密钥,避免硬编码:
import { SENDGRID_API_KEY } from '$env/static/private'; import sg from "@sendgrid/mail"; export function SendMail(mailData: MailDataFormat) { sg.setApiKey(SENDGRID_API_KEY); // ... }
内容的提问来源于stack exchange,提问作者HEDGEWIZARDS
相关产品推荐
相关产品推荐

