Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: lazy load sharp #65484

Merged
merged 2 commits into from
May 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 23 additions & 17 deletions packages/next/src/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,30 @@ const VECTOR_TYPES = [SVG]
const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
const BLUR_QUALITY = 70 // should match `next-image-loader`

let sharp: typeof import('sharp')

try {
sharp = require('sharp')
if (sharp && sharp.concurrency() > 1) {
// Reducing concurrency should reduce the memory usage too.
// We more aggressively reduce in dev but also reduce in prod.
// https://sharp.pixelplumbing.com/api-utility#concurrency
const divisor = process.env.NODE_ENV === 'development' ? 4 : 2
sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)))
let _sharp: typeof import('sharp')

function getSharp() {
if (_sharp) {
return _sharp
}
} catch (e: unknown) {
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
throw new Error(
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.'
)
try {
_sharp = require('sharp')
if (_sharp && _sharp.concurrency() > 1) {
// Reducing concurrency should reduce the memory usage too.
// We more aggressively reduce in dev but also reduce in prod.
// https://sharp.pixelplumbing.com/api-utility#concurrency
const divisor = process.env.NODE_ENV === 'development' ? 4 : 2
_sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)))
}
} catch (e: unknown) {
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
throw new Error(
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.'
)
}
throw e
}
throw e
return _sharp
}

export interface ImageParamsResult {
Expand Down Expand Up @@ -433,7 +439,7 @@ export async function optimizeImage({
}): Promise<Buffer> {
let optimizedBuffer = buffer

// Begin sharp transformation logic
const sharp = getSharp()
const transformer = sharp(buffer, {
sequentialRead: true,
})
Expand Down
Loading