@@ -39,24 +39,30 @@ const VECTOR_TYPES = [SVG]
39
39
const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
40
40
const BLUR_QUALITY = 70 // should match `next-image-loader`
41
41
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
52
47
}
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
58
64
}
59
- throw e
65
+ return _sharp
60
66
}
61
67
62
68
export interface ImageParamsResult {
@@ -433,7 +439,7 @@ export async function optimizeImage({
433
439
} ) : Promise < Buffer > {
434
440
let optimizedBuffer = buffer
435
441
436
- // Begin sharp transformation logic
442
+ const sharp = getSharp ( )
437
443
const transformer = sharp ( buffer , {
438
444
sequentialRead : true ,
439
445
} )
0 commit comments