UNPKG

2.58 kBJavaScriptView Raw
1const marked = require('./marked');
2const babel = require('babel-core');
3const renderer = new marked.Renderer();
4const yamlFront = require('yaml-front-matter')
5
6let res;
7const id = 'comp' + Math.random();
8
9const oldCode = renderer.code;
10
11// marked.setOptions({
12// highlight: function (code) {
13// return require('highlight.js').highlightAuto(code).value;
14// }
15// });
16
17function escape(html, encode) {
18 return html
19 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
20 .replace(/</g, '&lt;')
21 .replace(/>/g, '&gt;')
22 .replace(/"/g, '&quot;')
23 .replace(/'/g, '&#39;');
24}
25
26function unescape(html) {
27 // explicitly match decimal, hex, and named HTML entities
28 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
29 n = n.toLowerCase();
30 if (n === 'colon') return ':';
31 if (n.charAt(0) === '#') {
32 return n.charAt(1) === 'x'
33 ? String.fromCharCode(parseInt(n.substring(2), 16))
34 : String.fromCharCode(+n.substring(1));
35 }
36 return '';
37 });
38}
39
40renderer.code = (code, lang, escaped) => {
41
42
43 res = code;
44 // console.log(babel.transform(code, {
45 // plugins: ["transform-react-jsx"]
46 // }));
47 // const comp = babel.transform(code, {
48 // plugins: ["transform-react-jsx"]
49 // });
50
51 // eval(comp);
52
53
54 return `
55 <div>
56 <div id=${id}></div>
57 <pre><code>${escape(code)}</code></pre>
58 </div>`;
59}
60
61renderer.table = function (header, body) {
62 return '<table class="table table-striped">'+header+body+'</table>'
63}
64
65renderer.list = function(body, ordered) {
66 var type = ordered ? 'ol' : 'ul';
67 var styles = ordered ? 'upper-roman' : 'disc';
68 return '<' + type + ' style="padding-left:40px; list-style-type:'+ styles + ';" >\n' + body + '</' + type + '>\n';
69}
70
71function process(source) {
72 source = marked(source, {
73 renderer: renderer,
74 gfm: true,
75 tables: true,
76 breaks: true,
77 pedantic: false,
78 sanitize: true,
79 smartLists: true,
80 smartypants: false
81 });
82
83 const res = JSON.stringify(source);
84 return res;
85}
86
87
88module.exports = function(source, map){
89 this.cacheable && this.cacheable();
90
91 res = '';
92 const yaml = yamlFront.loadFront(source, 'content');
93 //对source进行解析
94 var md = process(yaml.content);
95 res += `\n export const md=${md}; \n export const id="${id}";`
96 console.log('----------------')
97 console.log(res);
98 console.log('--------------')
99
100 this.callback(null, res, map);
101 // return "module.exports = " + '{}';
102}
\No newline at end of file