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

混用CommonJS与ES模块导致Serverless函数调用失败求助

混合使用CommonJS与ES模块导致的导出错误

问题代码

const express = require("express");
const serverless = require("serverless-http");
import axios from 'axios'

const app = express();

.....

module.exports = app;
module.exports.handler = serverless(app);

报错信息

第一次错误

Function invocation failed: TypeError: Cannot assign to read only property 'exports' of object '#'

修改代码后的新错误

将module.exports = app;替换为export default app;后出现:

Function invocation failed: TypeError: Cannot set properties of undefined (setting 'handler')

原因及解决方法

问题核心是混合使用了CommonJS(require/module.exports)和ES模块(import/export)语法。Node.js会将包含import的文件识别为ES模块,此时module.exports是只读属性,无法直接赋值,这就是第一个错误的根源。

改成ES模块的export default app后,又试图给不存在的module.exports添加handler属性——ES模块体系里没有module.exports对象,因此触发第二个错误。

提供两种统一模块语法的解决方案:

方案一:统一使用CommonJS

将所有import替换为require,保留原有的导出方式:

const express = require("express");
const serverless = require("serverless-http");
const axios = require('axios')

const app = express();

// ... 你的业务代码

module.exports = app;
module.exports.handler = serverless(app);

方案二:统一使用ES模块

  1. 在项目根目录的package.json中添加"type": "module",声明项目使用ES模块
  2. 将所有CommonJS语法替换为ES模块语法:
import express from "express";
import serverless from "serverless-http";
import axios from 'axios'

const app = express();

// ... 你的业务代码

export default app;
export const handler = serverless(app);

内容的提问来源于stack exchange,提问作者vimuth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:23:21