UNPKG

3.46 kBJavaScriptView Raw
1'use strict';
2/**
3 * css文件处理
4 * - opacity透明兼容
5 * - 前缀处理
6 * - 文件签名
7 *
8 * @class Compile
9 * {
10 * src:'', <string> 源文件路径
11 * dist:'', <string> 输出路径
12 * }
13 */
14class 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 //配置写入到_ts.config
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, //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 //如果匹配到页面有title标签,则需要给文件添加签名
66 if(sTitle){
67 //html签名
68 html = html.replace(reTitle,sTitle[0] + '\r\n ' + signature);
69 };
70
71 //替换html开发模式添加的脚本
72 html = html.replace(reDev,'');
73
74 //替换jsx类型为js
75 html = html.replace(reJsx,'');
76
77 //去掉browser相关的js库
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}
116module.exports = Compile;