UNPKG

3.75 kBJavaScriptView Raw
1'use strict';
2/**
3 * html转换为html
4 *
5 * @class Pug2html
6 * {
7 * src:'', <string> jade文件路径
8 * dist:'', <string> html输出路径
9 * debug:true, [boolean] 默认:true,debug模式将会在页面底部添加fws开发模式额外信息,用于页面的自动刷新等……
10 * }
11 */
12class Pug2html{
13 constructor(option){
14 const _ts = this;
15
16 option = option || {};
17
18 let m = _ts.m = {
19 path:require('path'),
20 fs:require('fs-extra'),
21 pathInfo:require('./getPathInfo'),
22 replaceGlobal:require('./replaceGlobal')
23 },
24 config = _ts.config = {};
25
26 //配置写入到_ts.config
27 for(let i in option){
28 config[i] = option[i];
29 };
30
31 //默认开启debug模式
32 config.debug = config.debug === undefined ? true : config.debug;
33
34 //页面数据
35 config.data = config.data || {};
36
37 return new Promise((resolve,reject)=>{
38 let fileType = m.pathInfo(config.src).extension;
39 if(fileType === '.html' || fileType === '.htm'){
40 try {
41 _ts.init().then(v => {
42 resolve(v);
43 }).catch(e => {
44 reject(e);
45 });
46 } catch (error) {
47 reject({
48 status:'error',
49 msg:`初始化失败 ${m.path.join(fwsPath,'lib','html2html.js')}`,
50 info:error
51 });
52 };
53 }else{
54 reject({
55 status:'error',
56 msg:typeof config.src === 'string' ? `${config.src} 不是有效的html或html文件` : `参数传入错误`
57 });
58 };
59 });
60 }
61 init(){
62 const _ts = this,
63 m = _ts.m,
64 config = _ts.config;
65
66 let htmlRender = (resolve,reject)=>{
67 let html;
68 try {
69 html = m.fs.readFileSync(config.src).toString();
70 html += require('./echoHtmlDebug')();
71 } catch (err) {
72 reject({
73 status:'error',
74 msg:`编译出错 ${config.src}`,
75 info:err
76 });
77 };
78 if(html){
79 html = m.replaceGlobal(html);
80
81 //创建目录并写入文件
82 let distDir = m.path.dirname(config.dist);
83 m.fs.ensureDir(distDir,err => {
84 if(err){
85 reject({
86 status:'error',
87 msg:`创建失败 ${distDir}`,
88 info:err
89 });
90 };
91
92 //写入html文件
93 try {
94 m.fs.writeFileSync(config.dist,html);
95 resolve({
96 status:'success',
97 msg:`写入 ${config.dist}`,
98 data:html,
99 distPath:config.dist
100 });
101 } catch (err) {
102 reject({
103 status:'error',
104 msg:`写入失败 ${config.dist}`,
105 info:err,
106 distPath:config.dist
107 });
108 };
109 });
110 };
111 };
112
113 return new Promise(htmlRender);
114 }
115};
116module.exports = Pug2html;