【发布时间】:2021-09-27 20:18:57
【问题描述】:
我正在尝试使用svg2img 包创建一个将 SVG 转换为 PNG 的服务。我使用 vercel dev 让它在本地工作,但是当我尝试部署到 vercel 时,我总是收到这个错误:
2021-09-27T01:11:56.532Z e3a35069-8a51-4e1d-81b9-110e1b17e2be ERROR Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/api/node_modules/canvg/lib/index.js
require() of ES modules is not supported.
require() of /var/task/api/node_modules/canvg/lib/index.js from /var/task/api/node_modules/svg2img/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /var/task/api/node_modules/canvg/lib/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /var/task/api/node_modules/canvg/package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/var/task/api/node_modules/svg2img/index.js:1:13)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12) {
code: 'ERR_REQUIRE_ESM'
}
RequestId: e3a35069-8a51-4e1d-81b9-110e1b17e2be Error: Runtime exited with error: exit status 1
Runtime.ExitError
我的代码如下所示:
import svg2img from 'svg2img';
export default function(req, res) {
const url = req.query.url;
const width = req.query.width;
const height = req.query.height;
const size = Math.min(width, height);
svg2img(url, {width: size, height: size, preserveAspectRatio: true},
function(error, buffer) {
if (buffer) {
res.send(buffer);
}
});
};
这是 package.json
{
"name": "svg2png",
"version": "1.0.0",
"description": "convert svgs to pngs",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "me",
"license": "ISC",
"dependencies": {
"svg2img": "^0.9.3"
},
"type": "module"
}
【问题讨论】:
-
你确定这是整个错误,还是你没有粘贴整个错误?因为任何更多版本的 Node(LTS 14 或当前 16)都可以很好地使用模块,只要您记得在
package.json中将您的项目标记为使用现代 ES 模块,并声明"type": "module"。 -
@Mike'Pomax'Kamermans 添加了完整的错误信息
-
您是否在自己的
package.json中将您的项目标记为基于现代模块的代码库?因为看起来你没有,如果你想使用import语句,你 absolutely have to。 (编辑:对你的帖子进行很好的编辑,突然你的 package.json 有一个“类型”值。真的吗?如果是这样:你还有这个问题吗?) -
@Mike'Pomax'Kamermans 即使在我的 package.json 文件中有这个,我仍然遇到错误。试图破译错误,我想知道问题是否是 svg2img 没有使用模块导入画布?
-
我永远不会继续聊天。 SO 的重点是您的帖子是独立的,不需要 cmets 或聊天。
标签: javascript node.js npm vercel