Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache MDX compiler in the Webpack loader #1468

Merged
merged 1 commit into from
Apr 8, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions packages/loader/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
const {getOptions} = require('loader-utils')
const mdx = require('@mdx-js/mdx')
const {createCompiler} = require('@mdx-js/mdx')

const DEFAULT_RENDERER = `
import React from 'react'
import {mdx} from '@mdx-js/react'
`

const pragma = `
/* @jsxRuntime classic */
/* @jsx mdx */
/* @jsxFrag mdx.Fragment */
`
ChristianMurphy marked this conversation as resolved.
Show resolved Hide resolved

const compilerCache = new Map()
ChristianMurphy marked this conversation as resolved.
Show resolved Hide resolved

module.exports = async function (content) {
if (!compilerCache.has(this.query)) {
const {renderer = DEFAULT_RENDERER, ...opts} = getOptions(this)
compilerCache.set(this.query, [renderer, createCompiler(opts)])
}

const callback = this.async()
const options = Object.assign({}, getOptions(this), {
filepath: this.resourcePath
})
const [renderer, compiler] = compilerCache.get(this.query)

let result

try {
result = await mdx(content, options)
result = await compiler.process({
contents: content,
path: this.resourcePath
})
} catch (err) {
return callback(err)
}

const {renderer = DEFAULT_RENDERER} = options

const code = `${renderer}\n${result}`
const code = `${renderer}${pragma}${result}`
return callback(null, code)
}