Skip to content

Commit c4d812c

Browse files
authored
fix: lazy load sharp (#65484)
> [!NOTE] > This PR is easiest to review without whitespace. > See https://github.com/vercel/next.js/pull/65484/files?w=1 This PR fixes an issue where importing `image-optimization` was loading sharp but we don't want to load it until we attempt to optimize an image. So this PR changes it to lazy load on first invocation to avoid metadata trying to initialize sharp. ![image](https://github.com/vercel/next.js/assets/229881/61f45f3c-922a-45b6-8ba6-b32764fd0257) Closes NEXT-3355
1 parent d302c00 commit c4d812c

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

packages/next/src/server/image-optimizer.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,24 +39,30 @@ const VECTOR_TYPES = [SVG]
3939
const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
4040
const BLUR_QUALITY = 70 // should match `next-image-loader`
4141

42-
let sharp: typeof import('sharp')
43-
44-
try {
45-
sharp = require('sharp')
46-
if (sharp && sharp.concurrency() > 1) {
47-
// Reducing concurrency should reduce the memory usage too.
48-
// We more aggressively reduce in dev but also reduce in prod.
49-
// https://sharp.pixelplumbing.com/api-utility#concurrency
50-
const divisor = process.env.NODE_ENV === 'development' ? 4 : 2
51-
sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)))
42+
let _sharp: typeof import('sharp')
43+
44+
function getSharp() {
45+
if (_sharp) {
46+
return _sharp
5247
}
53-
} catch (e: unknown) {
54-
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
55-
throw new Error(
56-
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.'
57-
)
48+
try {
49+
_sharp = require('sharp')
50+
if (_sharp && _sharp.concurrency() > 1) {
51+
// Reducing concurrency should reduce the memory usage too.
52+
// We more aggressively reduce in dev but also reduce in prod.
53+
// https://sharp.pixelplumbing.com/api-utility#concurrency
54+
const divisor = process.env.NODE_ENV === 'development' ? 4 : 2
55+
_sharp.concurrency(Math.floor(Math.max(cpus().length / divisor, 1)))
56+
}
57+
} catch (e: unknown) {
58+
if (isError(e) && e.code === 'MODULE_NOT_FOUND') {
59+
throw new Error(
60+
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.'
61+
)
62+
}
63+
throw e
5864
}
59-
throw e
65+
return _sharp
6066
}
6167

6268
export interface ImageParamsResult {
@@ -433,7 +439,7 @@ export async function optimizeImage({
433439
}): Promise<Buffer> {
434440
let optimizedBuffer = buffer
435441

436-
// Begin sharp transformation logic
442+
const sharp = getSharp()
437443
const transformer = sharp(buffer, {
438444
sequentialRead: true,
439445
})

0 commit comments

Comments
 (0)