Skip to content
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
16 changes: 11 additions & 5 deletions packages/next/src/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,20 @@ 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')
let _sharp: typeof import('sharp')

function getSharp() {
if (_sharp) {
return _sharp
}
try {
sharp = require('sharp')
if (sharp && sharp.concurrency() > 1) {
_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)))
_sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)))
}
} catch (e: unknown) {
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
Expand All @@ -58,6 +62,8 @@ try {
}
throw e
}
return _sharp
}

export interface ImageParamsResult {
href: string
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