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