background
Why is there a need for code in Markdown to run in real time?
On our front end team, technical documentation is written in Markdown and often comes with a lot of sample code. We want people to run the sample code and see the results as they read the documentation.
demand
- Make the code in Markdown run and preview.
- Code can be edited online.
- Does not affect the overall document flow layout.
- React support, support code highlighting.
- Babel can be configured.
React-code-view: react-code-view: react-code-view: react-code-view: react-code-view:
IO /react-code-…
The principle of
- through
markdown-loader
与html-loader
Parse the Markdown document. - Get the code from the regular expression and hand it in
codemirror
- the
codemirror
The code is compiled by Babel and rendered to the specified container by reactdom.render.
The installation
npm install react-code-view
Copy the code
Configuration webpack
Support for Markdown-loader needs to be added to Webpack. Required installation:
npm install html-loader --save-dev
npm install markdown-loader --save-dev
npm install react-markdown-reader --save-dev
Copy the code
Webpack. Config. Js configuration
>=webpack 2.x +
const markdownRenderer = require('react-markdown-reader').renderer;
{
test: /\.md$/.use: [{
loader: 'html-loader'
}, {
loader: 'markdown-loader'.options: {
pedantic: true.renderer: markdownRenderer(/**languages:Array<string>**/)]}}}Copy the code
Languages Default value: [“javascript”, “bash”, “XML “,” CSS “, “markdown”, “less”];
Making: github.com/simonguo/re…
Add the Babel
Example code is usually used in ES2015+, React, etc., the code needs to be compiled in real time, so we introduce Babel in HTML:
<script type="text/javascript" src="/ / cdn.staticfile.org/babel-standalone/6.24.0/babel.min.js"></script>
Copy the code
The sample
import CodeView from 'react-code-view';
import '~react-code-view/lib/less/index.less';
import { Button } from 'rsuite';
<CodeView dependencies={{ Button }} >
{require('./example.md')}
</CodeView>
Copy the code
The source code is written in markdown, see example.md
The important thing to note here is that the code you want to run must be placed in
and
.
API
Name | Type | Default value | Description |
---|---|---|---|
dependencies | Object | Dependent components | |
showCode | boolean | true | According to the code |
babelTransformOptions | Object | { presets: [‘stage-0’, ‘react’, ‘es2015’] } | Babel Configuration parameteroptions |
Who’s in?
- React Suite