1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | class Compile{
|
15 | constructor(option){
|
16 | const _ts = this;
|
17 |
|
18 | option = option || {};
|
19 |
|
20 | let m = _ts.m = {
|
21 | fs:require('fs-extra'),
|
22 | path:require('path'),
|
23 | pathInfo:require('../lib/getPathInfo'),
|
24 | signature:require('../lib/signature')
|
25 | },
|
26 | config = _ts.config = {};
|
27 |
|
28 |
|
29 | for(let i in option){
|
30 | config[i] = option[i];
|
31 | };
|
32 | let src = config.src,
|
33 | dist = config.dist;
|
34 |
|
35 | return _ts.taskList();
|
36 | }
|
37 |
|
38 | taskList(){
|
39 | const _ts = this,
|
40 | m = _ts.m,
|
41 | config = _ts.config;
|
42 |
|
43 | return new Promise((resolve,reject)=>{
|
44 | let html,
|
45 | signature,
|
46 | sTitle,
|
47 | reTitle = /<title>.*<\/title>/,
|
48 | reDev = /<!--fws开发模式start-->(.|\r|\n)*<!--fws开发模式end-->/,
|
49 | reJsx = / type="text\/babel"/ig,
|
50 | reScript = /<script(.)*<\/script>/ig;
|
51 |
|
52 |
|
53 | if(m.pathInfo(config.src).extension === '.html'){
|
54 | html = m.fs.readFileSync(config.src).toString();
|
55 | signature = m.signature('.html');
|
56 | }else{
|
57 | reject({
|
58 | status:'error',
|
59 | msg:`${config.src} 不是有效的 HTML 文件`
|
60 | });
|
61 | };
|
62 |
|
63 | sTitle = html.match(reTitle);
|
64 |
|
65 |
|
66 | if(sTitle){
|
67 |
|
68 | html = html.replace(reTitle,sTitle[0] + '\r\n ' + signature);
|
69 | };
|
70 |
|
71 |
|
72 | html = html.replace(reDev,'');
|
73 |
|
74 |
|
75 | html = html.replace(reJsx,'');
|
76 |
|
77 |
|
78 | html = html.replace(reScript,word => {
|
79 | if(word.indexOf('browser') > -1){
|
80 | return '';
|
81 | };
|
82 | return word;
|
83 | });
|
84 |
|
85 |
|
86 | let distDir = m.path.dirname(config.dist);
|
87 |
|
88 | m.fs.ensureDir(distDir,err => {
|
89 | if(err){
|
90 | reject({
|
91 | status:'error',
|
92 | msg:`${distDir} 创建失败`,
|
93 | info:err
|
94 | });
|
95 | };
|
96 |
|
97 |
|
98 | try{
|
99 | m.fs.writeFileSync(config.dist,html);
|
100 | resolve({
|
101 | status:'success',
|
102 | msg:`写入 ${config.dist}`,
|
103 | data:html
|
104 | });
|
105 | }catch(err){
|
106 | reject({
|
107 | status:'error',
|
108 | msg:`${config.dist} 创建失败`,
|
109 | info:err
|
110 | });
|
111 | };
|
112 | })
|
113 | });
|
114 | }
|
115 | }
|
116 | module.exports = Compile;
|