mdToVue.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. const path = require('path');
  2. const fs = require('fs');
  3. const nodeFilelist = require('node-filelist');
  4. let { hashElement } = require('folder-hash');
  5. let { version } = require("../package.json");
  6. let marked = require('marked');
  7. let contrast = require('./contrast');
  8. let rimraf = require("rimraf");
  9. let Chokidar = require('chokidar');
  10. if (!marked) {
  11. console.log('you need npm i marked -D!');
  12. }
  13. class mdVue{
  14. constructor(options){
  15. let defaultSetting = {
  16. needCode:true,
  17. isbuild:true,
  18. hasMarkList:true
  19. };
  20. this.options =Object.assign(defaultSetting,options);
  21. this.rendererMd = new marked.Renderer();
  22. this.marked = marked;
  23. let _that = this;
  24. this.Articlehead = "";
  25. this.Articleheadcount = 0;
  26. this.needHandleFiles = null;
  27. this.cachePath = path.join("./cache",options.entry.split(path.sep).pop()+ '.cache');
  28. this.codeHandle();
  29. this.checkSelf().then(res=>{
  30. // 检查要编译的文件
  31. let ct = new contrast({
  32. entry:this.options.entry
  33. }).run().then(res=>{
  34. _that.needHandleFiles = res;
  35. _that.ishasOutFile(_that.options.output).then(res=>{
  36. _that.star();
  37. _that.filelisten()
  38. });
  39. })
  40. })
  41. }
  42. checkSelf(){
  43. let _that = this;
  44. return new Promise((resolve,reject)=>{
  45. new contrast({
  46. entry:path.join(__dirname,"mdToVue.js"),
  47. include:["*.js"]
  48. }).run().then(res=>{
  49. if(JSON.stringify(res) != "{}"){
  50. //有变动清除当前entry缓存,重新渲染
  51. rimraf(_that.cachePath,err=>{
  52. console.log(err)
  53. resolve()
  54. })
  55. }else{
  56. resolve()
  57. }
  58. })
  59. })
  60. }
  61. apply(){}
  62. filelisten(){
  63. let _that = this;
  64. let watcher = Chokidar.watch(_that.options.entry,{
  65. persistent: true,
  66. usePolling: true,
  67. });
  68. let log = console.dir.bind(console);
  69. let watchAction = function({event, eventPath}){
  70. // 这里进行文件更改后的操作
  71. if(/\.md$/.test(eventPath)){
  72. _that.vueDesWrite(eventPath)
  73. }
  74. }
  75. watcher.on('change', path => watchAction({event: 'change', eventPath: path}))
  76. .on('unlink', path => watchAction({event: 'remove', eventPath: path}));
  77. }
  78. star(){
  79. let _that = this;
  80. hashElement(_that.options.entry, {
  81. folders: { exclude: ['.*', 'node_modules', 'test_coverage'] },
  82. files: { include: ['*.md']},
  83. matchBasename: true
  84. }).then(hash => {
  85. nodeFilelist.read([_that.options.entry],{"ext":'md'}, res => {
  86. res.map((item,index) =>{
  87. _that.vueDesWrite(item.path)
  88. });
  89. });
  90. })
  91. }
  92. vueDesWrite(getpath){
  93. let _that = this;
  94. let fileSplits = getpath.split(path.sep);
  95. let fileName = fileSplits.pop();
  96. if(_that.isDoc(fileName)){
  97. fileName = fileSplits.pop();
  98. }else{
  99. fileName = fileName.replace(/\.md/,'');
  100. }
  101. if(_that.needHandleFiles[fileName]){
  102. // _that.read(item.path).then(res=>{
  103. // _that.headHandle();
  104. // _that.markHandle();
  105. // let html = _that.marked(res);
  106. // _that.write({
  107. // outsrc:_that.options.output,
  108. // name:fileName + '.vue',
  109. // html:html
  110. // });
  111. // })
  112. }
  113. _that.read(getpath).then(res=>{
  114. _that.headHandle();
  115. _that.markHandle();
  116. let html = _that.marked(res);
  117. _that.write({
  118. outsrc:_that.options.output,
  119. name:fileName + '.vue',
  120. html:html
  121. });
  122. })
  123. }
  124. isDoc(name){
  125. return (name == "doc.md") ? true : false;
  126. }
  127. read(src){
  128. return new Promise((resolve,reject)=>{
  129. fs.readFile(src, 'utf-8', (err, data) => {
  130. resolve(data)
  131. })
  132. })
  133. }
  134. write(param){
  135. let _that = this;
  136. return new Promise((resolve,reject)=>{
  137. let outPath = path.join(param.outsrc,param.name);
  138. let contexts = `<template>
  139. <div @click="dsCode">
  140. <div v-if="content" class="layer">
  141. <pre><span class="close-box" @click="closelayer"></span><div v-html="content"></div></pre>
  142. </div>`+ param.html + (_that.options.hasMarkList ? '<ul class="markList">' + _that.Articlehead + '</ul>' : '')+
  143. `<nut-backtop :right="50" :bottom="50"></nut-backtop>
  144. </div>
  145. </template><script>import root from '../root.js';
  146. export default {
  147. mixins:[root]
  148. }</script>`;
  149. _that.Articlehead = "";
  150. _that.Articleheadcount = 0;
  151. fs.writeFile(outPath ,contexts,'utf8',(err,res)=>{ })
  152. })
  153. }
  154. ishasOutFile(outPath){
  155. return new Promise((resolve,reject)=>{
  156. fs.stat(outPath,(err,res)=>{
  157. if(err){
  158. fs.mkdir(outPath,err=>{
  159. if(err){
  160. reject(err)
  161. }else{
  162. resolve(true)
  163. }
  164. })
  165. }else{
  166. resolve(true)
  167. }
  168. })
  169. })
  170. }
  171. headHandle(){
  172. let _that = this;
  173. let options = _that.options;
  174. _that.rendererMd.heading = function (text,level){
  175. let headcode = '<i class="qrcode"><a :href="demourl"><span>请使用手机扫码体验</span><img :src="codeurl" alt=""></a></i>';
  176. let codeHead = `<h1>` + text +headcode+`</h1>`;
  177. let normal = `<h`+level+`>`+text+`</h`+level+`>`;
  178. let Articleheadcounts = null;
  179. if(level==2&&_that.options.hasMarkList){
  180. Articleheadcounts = _that.Articleheadcount;
  181. Articleheadcounts++;
  182. _that.Articleheadcount = Articleheadcounts;
  183. let headmsg = _that.Articlehead;
  184. headmsg +=`<li @click="leavelchose(`+Articleheadcounts+`)" :class="levalcur==`+Articleheadcounts+`?'cur':''" class="level`+Articleheadcounts+'"><a href="#head'+Articleheadcounts+'">'+text.substr(0,10)+'</a></li>';
  185. _that.Articlehead = headmsg;
  186. }
  187. let maskIdHead = "<h"+level+" class='visibility' id='head"+Articleheadcounts+"'>"+ text +"</h"+level+">";
  188. //判断条件
  189. if(_that.options.hasMarkList && _that.options.needCode){
  190. if(level == 1){
  191. return codeHead;
  192. }else if(level == 2){
  193. return maskIdHead;
  194. } else{
  195. return normal;
  196. }
  197. }else if(_that.options.hasMarkList && !_that.options.needCode){
  198. if(level !=1){
  199. return maskIdHead;
  200. } else{
  201. return normal;
  202. }
  203. }else if(!_that.options.hasMarkList && _that.options.needCode){
  204. if(level == 1){
  205. return codeHead;
  206. } else{
  207. return normal;
  208. }
  209. }else if(!_that.options.hasMarkList && !_that.options.needCode){
  210. return normal;
  211. }
  212. };
  213. }
  214. codeHandle(){
  215. this.rendererMd.code = function (code, infostring, escaped) {
  216. var lang = (infostring || '').match(/\S*/)[0];
  217. if (this.options.highlight) {
  218. var out = this.options.highlight(code, lang);
  219. if (out != null && out !== code) {
  220. escaped = true;
  221. code = out;
  222. }
  223. }
  224. if (!lang) {
  225. return '<pre><code>'
  226. + (escaped ? code : escape(code, true))
  227. + '</code></pre>';
  228. }
  229. if (lang === 'html') {
  230. code = code.replace(/@latest/g, '@' + version)
  231. }
  232. return '<hide><pre class="prettyprint"><span class="lang">' + lang + '</span><div class="code-wrapper"><code class="'
  233. + this.options.langPrefix
  234. + escape(lang, true)
  235. + '">'
  236. + (escaped ? code : escape(code, true))
  237. + '</code></div><i class="copy" copy="copy" data-clipboard-action="copy" data-clipboard-target="code" title="复制代码"></i><i toast="toast" title="全屏"></i></pre></hide>\n';
  238. };
  239. }
  240. markHandle(){
  241. let _that = this;
  242. this.marked.setOptions({
  243. renderer: _that.rendererMd,
  244. highlight: function (code) {
  245. return require('highlight.js').highlightAuto(code).value;
  246. },
  247. tables: true
  248. });
  249. }
  250. };
  251. module.exports = mdVue;