Skip to content

安裝

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);
  });

常見問題

安裝失敗

如果遇到安裝問題,請嘗試:

  1. 更新 Node.js: 確保使用最新版本
  2. 清除緩存: npm cache clean --force
  3. 刪除 node_modules: 刪除後重新安裝
  4. 檢查網絡: 確保可以訪問 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。

基於 Apache 2.0 許可證發布