Skip to content

Commit

Permalink
Add processor cache in webpack loader
Browse files Browse the repository at this point in the history
Related-to: mdx-js/mdx#1468.
  • Loading branch information
wooorm committed Jan 23, 2022
1 parent 94fc1df commit decafe9
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions lib/integration/webpack.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
/**
* @typedef {import('vfile').VFileCompatible} VFileCompatible
* @typedef {import('vfile').VFile} VFile
* @typedef {import('webpack').LoaderContext<unknown>} LoaderContext
* @typedef {import('../compile.js').CompileOptions} CompileOptions
* @typedef {Pick<CompileOptions, 'SourceMapGenerator'>} Defaults
* @typedef {Omit<CompileOptions, 'SourceMapGenerator'>} Options
* @typedef {(vfileCompatible: VFileCompatible) => Promise<VFile>} Process
*/

import {SourceMapGenerator} from 'source-map'
import {compile} from '../compile.js'
import {createFormatAwareProcessors} from '../util/create-format-aware-processors.js'

/** @type {WeakMap<CompileOptions, Process>} */
const cache = new WeakMap()

/**
* A Webpack (4+) loader for xdm.
Expand All @@ -21,11 +27,16 @@ export function loader(value, callback) {
/** @type {Defaults} */
const defaults = this.sourceMap ? {SourceMapGenerator} : {}
const options = /** @type {CompileOptions} */ (this.getOptions())
compile({value, path: this.resourcePath}, {...defaults, ...options}).then(
(file) => {
callback(null, file.value, file.map)
return file
},
callback
)
const config = {...defaults, ...options}
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)
}

0 comments on commit decafe9

Please sign in to comment.