Unverified Commit c4d812cc authored by Steven's avatar Steven Committed by GitHub

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
parent d302c00d
...@@ -39,24 +39,30 @@ const VECTOR_TYPES = [SVG] ...@@ -39,24 +39,30 @@ const VECTOR_TYPES = [SVG]
const BLUR_IMG_SIZE = 8 // should match `next-image-loader` const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
const BLUR_QUALITY = 70 // should match `next-image-loader` const BLUR_QUALITY = 70 // should match `next-image-loader`
let sharp: typeof import('sharp') let _sharp: typeof import('sharp')
try { function getSharp() {
sharp = require('sharp') if (_sharp) {
if (sharp && sharp.concurrency() > 1) { return _sharp
// 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) { try {
if (isError(e) && e.code === 'MODULE_NOT_FOUND') { _sharp = require('sharp')
throw new Error( if (_sharp && _sharp.concurrency() > 1) {
'Module `sharp` not found. Please run `npm install --cpu=wasm32 sharp` to install it.' // 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 { export interface ImageParamsResult {
...@@ -433,7 +439,7 @@ export async function optimizeImage({ ...@@ -433,7 +439,7 @@ export async function optimizeImage({
}): Promise<Buffer> { }): Promise<Buffer> {
let optimizedBuffer = buffer let optimizedBuffer = buffer
// Begin sharp transformation logic const sharp = getSharp()
const transformer = sharp(buffer, { const transformer = sharp(buffer, {
sequentialRead: true, sequentialRead: true,
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment