From e0b697ab8e2554f77a52ba3ec78351c829de58f4 Mon Sep 17 00:00:00 2001 From: Titus Date: Tue, 25 Jan 2022 09:36:19 +0100 Subject: [PATCH] Add processor cache in webpack loader (#1912) Backports: wooorm/xdm@decafe9. Related-to: GH-1468. --- packages/loader/lib/index.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/packages/loader/lib/index.js b/packages/loader/lib/index.js index 76906c8b7..5ab51e0fb 100644 --- a/packages/loader/lib/index.js +++ b/packages/loader/lib/index.js @@ -1,12 +1,18 @@ /** + * @typedef {import('vfile').VFileCompatible} VFileCompatible + * @typedef {import('vfile').VFile} VFile * @typedef {import('@mdx-js/mdx').CompileOptions} CompileOptions * @typedef {Pick} Defaults * @typedef {Omit} Options * @typedef {import('webpack').LoaderContext} LoaderContext + * @typedef {(vfileCompatible: VFileCompatible) => Promise} Process */ import {SourceMapGenerator} from 'source-map' -import {compile} from '@mdx-js/mdx' +import {createFormatAwareProcessors} from '@mdx-js/mdx/lib/util/create-format-aware-processors.js' + +/** @type {WeakMap} */ +const cache = new WeakMap() /** * A Webpack (5+) loader for MDX. @@ -21,20 +27,25 @@ export function loader(value, callback) { /** @type {Defaults} */ const defaults = this.sourceMap ? {SourceMapGenerator} : {} const options = /** @type {CompileOptions} */ (this.getOptions()) + const config = {...defaults, ...options} /* Removed option. */ /* c8 ignore next 5 */ - if ('renderer' in options) { + if ('renderer' in config) { throw new Error( '`options.renderer` is no longer supported. Please see for more information' ) } - compile({value, path: this.resourcePath}, {...defaults, ...options}).then( - (file) => { - callback(null, file.value, file.map) - return file - }, - callback - ) + let process = cache.get(config) + + if (!process) { + process = createFormatAwareProcessors(config).process + cache.set(config, process) + } + + process({value, path: this.resourcePath}).then((file) => { + callback(null, file.value, file.map) + return file + }, callback) }