安装
Sharp 是一个高性能的 Node.js 图像处理库,支持多种图像格式和操作。
系统要求
- Node.js: 版本 18.0.0 或更高
- 平台: Windows, macOS, Linux
- 架构: x64, ARM64
安装方法
使用 npm
bash
npm install sharp
使用 pnpm
bash
pnpm add sharp
使用 yarn
bash
yarn add sharp
预编译二进制文件
Sharp 会自动下载适合您平台的预编译二进制文件。如果安装下载失败,您可以选择更改包含 sharp 和 libvips 二进制文件的镜像站点:
设置镜像源
bash
# 使用淘宝镜像
#pnpm
pnpm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
pnpm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
#npm
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
# 或使用 GitHub 镜像
npm config set sharp_binary_host "https://github.com/lovell/sharp/releases/download"
手动安装
如果自动安装失败,您可以手动安装:
bash
# 清除缓存
npm cache clean --force
# 重新安装
npm install sharp --ignore-scripts=false
验证安装
创建一个测试文件来验证安装:
javascript
// test-sharp.js
import sharp from 'sharp';
console.log('Sharp 版本:', sharp.versions.sharp);
console.log('libvips 版本:', sharp.versions.vips);
// 测试基本功能
sharp('test.jpg')
.resize(100, 100)
.toBuffer()
.then(() => {
console.log('Sharp 安装成功!');
})
.catch((err) => {
console.error('Sharp 安装失败:', err);
});
常见问题
安装失败
如果遇到安装问题,请尝试:
- 更新 Node.js: 确保使用最新版本
- 清除缓存:
npm cache clean --force
- 删除 node_modules: 删除后重新安装
- 检查网络: 确保可以访问 npm 仓库
平台特定问题
Windows
- 确保安装了 Visual Studio Build Tools
- 如果使用 WSL,确保在 Linux 环境中安装
macOS
- 确保安装了 Xcode Command Line Tools
- 如果使用 M1/M2 芯片,确保使用 ARM64 版本
Linux
- 安装必要的开发工具:
sudo apt-get install build-essential
- 对于 Alpine Linux:
apk add --no-cache vips-dev
开发环境
TypeScript 支持
Sharp 包含完整的 TypeScript 定义:
bash
npm install --save-dev @types/node
开发工具
推荐使用以下工具进行开发:
- VS Code: 优秀的 TypeScript 支持
- ESLint: 代码质量检查
- Prettier: 代码格式化
下一步
安装完成后,查看 快速开始指南 了解如何使用 Sharp。