Created
January 16, 2017 23:54
-
-
Save Xiphe/7e6915a458fbf880b6501bcb5b6b8fdc to your computer and use it in GitHub Desktop.
seamlessly embedded JSX in markdown files on the fly #hipsterstuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const md = require('markdown-it')(); | |
const mdJsxPlugin = require('markdown-it-jsx'); | |
const reactJsx = require('react-jsx'); | |
const React = require('react'); | |
const reactDom = require('react-dom/server'); | |
const originalCreateElement = React.createElement; | |
md.use(mdJsxPlugin); | |
const jsxString = md.render(` | |
## Test | |
<Hello postfix={'!'}>World</Hello> | |
<p>How are you{getQuestionMark()}</p> | |
<Hello postfix='?'><Hello postfix="??" /> | |
<Hello postfix="???">Universe</Hello> | |
</Hello> | |
<div class="lorem">ipsum</div> | |
<span class='dolor'>sit</span> | |
<div className="this-is-a-table"> | |
\`\`\`markdown | |
Funky | Table | |
------|------ | |
a | b | |
\`\`\` | |
</div> | |
`); | |
const Hello = (props) => { | |
return originalCreateElement('span', null, [ | |
'Hello ', | |
props.children, | |
props.postfix, | |
]); | |
}; | |
const getQuestionMark = () => '?'; | |
const BetterH2 = (props) => { | |
return originalCreateElement('h1', props); | |
}; | |
function replaceType(type) { | |
if (type === 'h2') { | |
return BetterH2; | |
} | |
return type; | |
} | |
const ProxyReact = { | |
createElement(someType) { | |
const newArgs = [].slice.call(arguments); | |
newArgs.splice(0, 1, replaceType(someType)); | |
return originalCreateElement.apply(ProxyReact, newArgs); | |
}, | |
}; | |
const parsedJsx = reactJsx.server(`<div>${jsxString}</div>`)({ React: ProxyReact, Hello, getQuestionMark }); | |
console.log(reactDom.renderToStaticMarkup(parsedJsx)); | |
/* | |
<div> | |
<h1>Test</h1> | |
<span>Hello World!</span> | |
<p>How are you?</p> | |
<span> | |
Hello <span>Hello ??</span> | |
<span>Hello Universe???</span>? | |
</span> | |
<pre><code>&lt;div class=&quot;lorem&quot;&gt;ipsum&lt;/div&gt; | |
&lt;span class='dolor'&gt;sit&lt;/span&gt; | |
</code></pre> | |
<div class="this-is-a-table"><pre><code class="language-markdown">Funky | Table | |
------|------ | |
a | b | |
</code></pre> | |
</div> | |
</div> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment