Skip to content

Commit

Permalink
Add processor cache in webpack loader (#1912)
Browse files Browse the repository at this point in the history
Backports: wooorm/xdm@decafe9.

Related-to: GH-1468.
  • Loading branch information
wooorm committed Jan 25, 2022
1 parent 4a48f1f commit e0b697a
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions 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<CompileOptions, 'SourceMapGenerator'>} Defaults
* @typedef {Omit<CompileOptions, 'SourceMapGenerator'>} Options
* @typedef {import('webpack').LoaderContext<unknown>} LoaderContext
* @typedef {(vfileCompatible: VFileCompatible) => Promise<VFile>} 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<CompileOptions, Process>} */
const cache = new WeakMap()

/**
* A Webpack (5+) loader for MDX.
Expand All @@ -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 <https://mdxjs.com/migrating/v2/> 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)
}

1 comment on commit e0b697a

@vercel
Copy link

@vercel vercel bot commented on e0b697a Jan 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

Please sign in to comment.