diff --git a/packages/mdx/mdx-hast-to-jsx.js b/packages/mdx/mdx-hast-to-jsx.js index 7a6ebb476..1b86a15ce 100644 --- a/packages/mdx/mdx-hast-to-jsx.js +++ b/packages/mdx/mdx-hast-to-jsx.js @@ -95,21 +95,29 @@ function toJSX(node, parentNode = {}, options = {}) { jsxNodes.push(childNode) } - return ( importNodes.map(childNode => toJSX(childNode, node)).join('\n') + '\n' + exportNodes.map(childNode => toJSX(childNode, node)).join('\n') + '\n' + - (skipExport ? '' : 'export default ({components, ...props}) => ') + - `${jsxNodes - .map(childNode => toJSX(childNode, node)) - .join('')}` + `${ + skipExport ? '' : 'export default' + } class MDXContent extends React.Component { + constructor() { + this.layout = ${layout} + } + render() { + return ${jsxNodes + .map(childNode => toJSX(childNode, node)) + .join('')} + + } +}` ) } - // Recursively walk through children if (node.children) { children = node.children diff --git a/packages/mdx/package.json b/packages/mdx/package.json index 4a5336c36..2f9301d9e 100644 --- a/packages/mdx/package.json +++ b/packages/mdx/package.json @@ -45,7 +45,8 @@ "@babel/plugin-syntax-jsx": "^7.0.0", "@mapbox/rehype-prism": "^0.3.0", "hast-util-select": "^3.0.0", - "jest": "^23.0.0", + "jest": "^23.6.0", + "prettier": "^1.14.2", "rehype-katex": "^1.1.1", "remark-math": "^1.0.4" }, diff --git a/packages/mdx/test/index.test.js b/packages/mdx/test/index.test.js index fce6034e9..984e83da5 100644 --- a/packages/mdx/test/index.test.js +++ b/packages/mdx/test/index.test.js @@ -7,6 +7,7 @@ const {select} = require('hast-util-select') const prism = require('@mapbox/rehype-prism') const math = require('remark-math') const katex = require('rehype-katex') +const prettier = require('prettier') const fixtureBlogPost = fs.readFileSync( path.join(__dirname, './fixtures/blog-post.md') @@ -42,6 +43,26 @@ it('Should compile sample blog post', async () => { parse(result) }) +it('Should match sample blog post snapshot', async () => { + const result = await mdx(`# Hello World`) + + expect(prettier.format(result, {parser: 'babylon'})).toMatchInlineSnapshot(` +"export default class MDXContent extends React.Component { + constructor() { + this.layout = undefined; + } + render() { + return ( + + {\`Hello World\`} + + ); + } +} +" +`) +}) + it('Should render blockquote correctly', async () => { const result = await mdx('> test\n\n> `test`') diff --git a/packages/runtime/src/index.js b/packages/runtime/src/index.js index 28e170b4c..978be120f 100644 --- a/packages/runtime/src/index.js +++ b/packages/runtime/src/index.js @@ -31,7 +31,14 @@ export default ({ const keys = Object.keys(fullScope) const values = keys.map(key => fullScope[key]) // eslint-disable-next-line no-new-func - const fn = new Function('_fn', 'React', ...keys, `return ${code}`) + const fn = new Function( + '_fn', + 'React', + ...keys, + `${code} + + return React.createElement(MDXContent);` + ) return fn({}, React, ...values) }