UNPKG

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