Skip to content

Commit

Permalink
Loader renderer option (#725)
Browse files Browse the repository at this point in the history
* add prepend option

* add docs

* docs update / use `renderer`
  • Loading branch information
axdg authored and johno committed Aug 13, 2019
1 parent f854f63 commit b77e294
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 6 deletions.
17 changes: 11 additions & 6 deletions packages/loader/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
const {getOptions} = require('loader-utils')
const mdx = require('@mdx-js/mdx')

module.exports = async function(content) {
const DEFAULT_RENDERER = `
import React from 'react'
import { mdx } from '@mdx-js/react'
`

const loader = async function(content) {
const callback = this.async()
const options = Object.assign({}, getOptions(this), {
filepath: this.resourcePath
})

let result

try {
Expand All @@ -14,11 +20,10 @@ module.exports = async function(content) {
return callback(err)
}

const code = `/* @jsx mdx */
import React from 'react'
import { mdx } from '@mdx-js/react'
${result}
`
const {renderer = DEFAULT_RENDERER} = options

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

module.exports = loader
47 changes: 47 additions & 0 deletions packages/loader/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,53 @@ module: {
}
```

The `renderer` option specifies a string that will be prepended to the generated source allowing for the use of any `createElement` implementation. By default, that string is:

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

Using the `renderer` option, one can swap out React for another implementation. The example below wraps a generic JSX compatible function named `h`.

```js
const renderer = `
import { h } from 'generic-implementation'
const mdx = (function (createElement) {
return function (name, props, ...children) {
if (typeof name === 'string') {
if (name === 'wrapper') return children.map(createElement)
if (name === 'inlineCode') return createElement('code', props, ...children)
}
return createElement(name, props, ...children)
}
}(h))
`

// ...
module: {
rules: [
// ...
{
test: /\.mdx?$/,
use: [
'babel-loader',
{
loader: '@mdx-js/loader'
options: {
renderer,
}
}
]
}
]
}
```

For more information on why this is required, see [this post](https://mdxjs.com/blog/custom-pragma).

## Contribute

See the [Support][] and [Contributing][] guidelines on the MDX website for ways
Expand Down

0 comments on commit b77e294

Please sign in to comment.