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

Node项目构建报错:无法解析node-fetch依赖的node:http模块

问题

我是Node.js新手,开发了一个仅引入node-fetch模块的Chrome扩展。此前执行yarn build构建包含所有必要依赖的包从未出现问题,但当前构建时控制台抛出如下错误:

🚨  /Users/me/Documents/GitHub/my-project/node_modules/node-fetch/src/index.js:9:17: Cannot resolve dependency 'node:http'
   7 |  */
   8 |
>  9 | import http from 'node:http';
     |                 ^
  10 | import https from 'node:https';
  11 | import zlib from 'node:zlib';
  12 | import Stream, {PassThrough, pipeline as pump} from 'node:stream';
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: "build:bg" exited with 1.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

该错误来自我的node_modules目录下的node-fetch文件,而非我编写的代码。我的package.json仅声明了以下一个依赖:

"dependencies": {
    "node-fetch": "^3.3.0"
  }

我尝试手动安装报错中提及的模块并添加到依赖中,但毫无效果。请问我遗漏了什么?

解答
  • node-fetch v3.x版本仅适配Node.js环境,它依赖node:http、node:https这类Node.js专属核心模块,而Chrome扩展运行在浏览器环境,不存在这些模块,所以构建时会报错。
  • 你之前构建成功应该是使用了node-fetch的v2.x版本,v2.x同时兼容浏览器和Node.js环境,不会引入这些Node.js专属模块。
  • 解决步骤:
    1. 卸载当前的node-fetch v3.x:yarn remove node-fetch
    2. 安装兼容浏览器的v2.x版本:yarn add node-fetch@2
  • 额外建议:Chrome扩展本身支持原生fetch API,完全可以直接使用浏览器自带的fetch,无需引入node-fetch模块,这样更轻量且无环境兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:50:17