@@ -7,6 +7,7 @@ import type { MdxjsEsm } from 'mdast-util-mdxjs-esm';
77import { joinPath , slash } from '@/utils/path' ;
88import type { ISizeCalculationResult } from 'image-size/types/interface' ;
99import { imageSizeFromFile } from 'image-size/fromFile' ;
10+ import type { MdxJsxFlowElement } from 'mdast-util-mdx-jsx' ;
1011
1112const VALID_BLUR_EXT = [ '.jpeg' , '.png' , '.webp' , '.avif' , '.jpg' ] ;
1213const EXTERNAL_URL_REGEX = / ^ h t t p s ? : \/ \/ / ;
@@ -18,12 +19,23 @@ export interface RemarkImageOptions {
1819 publicDir ?: string ;
1920
2021 /**
21- * Preferred placeholder type
22+ * Preferred placeholder type, only available with `useImport` + local images.
2223 *
2324 * @defaultValue 'blur'
2425 */
2526 placeholder ?: 'blur' | 'none' ;
2627
28+ /**
29+ * Define how to handle errors when fetching image size.
30+ *
31+ * - `error` (default): throw an error.
32+ * - `ignore`: do absolutely nothing (Next.js Image component may complain).
33+ * - `hide`: remove that image element.
34+ *
35+ * @defaultValue 'error'
36+ */
37+ onError ?: 'error' | 'hide' | 'ignore' | ( ( error : Error ) => void ) ;
38+
2739 /**
2840 * Import images in the file, and let bundlers handle it.
2941 *
@@ -56,6 +68,7 @@ export function remarkImage({
5668 placeholder = 'blur' ,
5769 external = true ,
5870 useImport = true ,
71+ onError = 'error' ,
5972 publicDir = path . join ( process . cwd ( ) , 'public' ) ,
6073} : RemarkImageOptions = { } ) : Transformer < Root , Root > {
6174 return async ( tree , file ) => {
@@ -110,15 +123,31 @@ export function remarkImage({
110123 value : size . height . toString ( ) ,
111124 } ,
112125 ] ,
113- } ) ;
126+ children : [ ] ,
127+ } satisfies MdxJsxFlowElement ) ;
114128 } )
115129 . catch ( ( e ) => {
116- throw new Error (
117- `[Remark Image] Failed obtain image size for ${ url } (public directory configured as ${ publicDir } )` ,
118- {
119- cause : e ,
120- } ,
121- ) ;
130+ if ( onError === 'hide' ) {
131+ Object . assign ( node , {
132+ type : 'mdxJsxFlowElement' ,
133+ name : null ,
134+ attributes : [ ] ,
135+ children : [ ] ,
136+ } satisfies MdxJsxFlowElement ) ;
137+ return ;
138+ }
139+
140+ if ( onError === 'ignore' ) return ;
141+ if ( onError === 'error' ) {
142+ throw new Error (
143+ `[Remark Image] Failed obtain image size for ${ url } (public directory configured as ${ publicDir } )` ,
144+ {
145+ cause : e ,
146+ } ,
147+ ) ;
148+ }
149+
150+ onError ( e ) ;
122151 } ) ;
123152
124153 promises . push ( task ) ;
0 commit comments