11/**
2+ * @typedef {import('vfile').VFileCompatible } VFileCompatible
3+ * @typedef {import('vfile').VFile } VFile
24 * @typedef {import('@mdx-js/mdx').CompileOptions } CompileOptions
35 * @typedef {Pick<CompileOptions, 'SourceMapGenerator'> } Defaults
46 * @typedef {Omit<CompileOptions, 'SourceMapGenerator'> } Options
57 * @typedef {import('webpack').LoaderContext<unknown> } LoaderContext
8+ * @typedef {(vfileCompatible: VFileCompatible) => Promise<VFile> } Process
69 */
710
811import { SourceMapGenerator } from 'source-map'
9- import { compile } from '@mdx-js/mdx'
12+ import { createFormatAwareProcessors } from '@mdx-js/mdx/lib/util/create-format-aware-processors.js'
13+
14+ /** @type {WeakMap<CompileOptions, Process> } */
15+ const cache = new WeakMap ( )
1016
1117/**
1218 * A Webpack (5+) loader for MDX.
@@ -21,20 +27,25 @@ export function loader(value, callback) {
2127 /** @type {Defaults } */
2228 const defaults = this . sourceMap ? { SourceMapGenerator} : { }
2329 const options = /** @type {CompileOptions } */ ( this . getOptions ( ) )
30+ const config = { ...defaults , ...options }
2431
2532 /* Removed option. */
2633 /* c8 ignore next 5 */
27- if ( 'renderer' in options ) {
34+ if ( 'renderer' in config ) {
2835 throw new Error (
2936 '`options.renderer` is no longer supported. Please see <https://mdxjs.com/migrating/v2/> for more information'
3037 )
3138 }
3239
33- compile ( { value, path : this . resourcePath } , { ...defaults , ...options } ) . then (
34- ( file ) => {
35- callback ( null , file . value , file . map )
36- return file
37- } ,
38- callback
39- )
40+ let process = cache . get ( config )
41+
42+ if ( ! process ) {
43+ process = createFormatAwareProcessors ( config ) . process
44+ cache . set ( config , process )
45+ }
46+
47+ process ( { value, path : this . resourcePath } ) . then ( ( file ) => {
48+ callback ( null , file . value , file . map )
49+ return file
50+ } , callback )
4051}
0 commit comments