解决 npm install canvas@2.11.2 失败的问题

文章目录

  • 前言
  • [Mac 版](#Mac 版)
    • 安装系统依赖(macOS)
    • [确保 Xcode 命令行工具已安装](#确保 Xcode 命令行工具已安装)
    • [将 npm 镜像源更改为淘宝镜像源](#将 npm 镜像源更改为淘宝镜像源)
    • [全局安装 node-gyp](#全局安装 node-gyp)
    • [清除 npm 缓存并开始安装](#清除 npm 缓存并开始安装)
    • 安装成功
  • [Windows 版](#Windows 版)
    • [安装 vscode](#安装 vscode)
    • [将 npm 镜像源更改为淘宝镜像源](#将 npm 镜像源更改为淘宝镜像源)
    • [全局安装 node-gyp](#全局安装 node-gyp)
    • [清除 npm 缓存并开始安装](#清除 npm 缓存并开始安装)
    • 安装成功

前言

项目中使用了 canvas npm包来实现 node 服务端数据成图的功能。但是在项目中使用 npm install 安装失败,经过各种和 AI 沟通的尝试后,终于指定版本的 canvas 安装成功,项目也运行成功,在此记录一下安装方法。


Mac 版

  • 操作系统:MacOS Sequoia 15.5
  • node版本:v15.14.0
  • npm版本:v7.7.6

安装系统依赖(macOS)

canvas 需要系统级图形库支持,使用Homebrew安装:

bash 复制代码
brew install pkg-config cairo pango libpng jpeg giflib librsvg

确保 Xcode 命令行工具已安装

bash 复制代码
xcode-select --install

将 npm 镜像源更改为淘宝镜像源

bash 复制代码
# 查看当前配置
npm config get registry
# 设置为淘宝镜像
npm config set registry https://registry.npmmirror.com/
# 恢复为官方镜像
npm config set registry https://registry.npmjs.org/

全局安装 node-gyp

node-gyp是一个Node.js的原生插件构建工具,用于编译C++扩展模块。很多Node.js模块,比如canvas,都包含C++代码,需要编译后才能在特定平台上运行。

bash 复制代码
npm install -g node-gyp

清除 npm 缓存并开始安装

bash 复制代码
# 清除npm缓存
npm cache clean --force
npm cache verify
# 删除指定文件
rm -rf node_modules package-lock.json
npm install

安装成功

执行 npm install 后,需要等待10分钟左右才会安装成功,进程会卡在 core-js@2.6.12 处,如下图:

等待中截图

安装成功截图


Windows 版

  • 操作系统:Windows 11
  • node版本:v15.14.0
  • npm版本:v7.7.6

安装 vscode

官网下载地址

将 npm 镜像源更改为淘宝镜像源

bash 复制代码
# 查看当前配置
npm config get registry
# 设置为淘宝镜像
npm config set registry https://registry.npmmirror.com/
# 恢复为官方镜像
npm config set registry https://registry.npmjs.org/

全局安装 node-gyp

node-gyp是一个Node.js的原生插件构建工具,用于编译C++扩展模块。很多Node.js模块,比如canvas,都包含C++代码,需要编译后才能在特定平台上运行。

bash 复制代码
npm install -g node-gyp

清除 npm 缓存并开始安装

bash 复制代码
# 清除npm缓存
npm cache clean --force
npm cache verify
# 删除指定文件
rmdir /s /q node_modules && del /f /q package-lock.json
npm install

安装成功

执行 npm install 后,很快就安装成功了,不会像 Mac 端卡着。如下图:

相关推荐
duandashuaige2 天前
解决用electron打包Vue工程(Vite)报错electron : Failed to load URL : xxx... with error : ERR _CONNECTION_REFUSED
javascript·typescript·electron·npm·vue·html
weixin_405023373 天前
包资源管理器NPM 使用
前端·npm·node.js
小于小于09123 天前
npx 与 npm 区别
前端·npm·node.js
亮子AI4 天前
【npm】npm install 产生软件包冲突怎么办?(详细步骤)
前端·npm·node.js
Rhys..5 天前
JS - npm init
开发语言·javascript·npm
夏天想5 天前
复制了一个vue的项目然后再这个基础上修改。可是通过npm run dev运行之前的老项目,发现运行的竟然是拷贝后的项目。为什么会这样?
前端·vue.js·npm
一枚前端小能手6 天前
📦 从npm到yarn到pnpm的演进之路 - 包管理器实现原理深度解析
前端·javascript·npm
scorpion_V7 天前
VScode 中执行 npm 报错的问题
ide·vscode·npm
FreeBuf_7 天前
攻击者利用Discord Webhook通过npm、PyPI和Ruby软件包构建隐蔽C2通道
前端·npm·ruby
程序铺子8 天前
如何使用 npm 安装 sqlite3 和 canvas 这些包
javascript·npm·node.js