forked from Chellyyy/myBundler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
myBundler.js
318 lines (313 loc) · 10.6 KB
/
myBundler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
* Create by Chelly
* 2020/4/21
*/
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');
const minifyHTML = require('html-minifier').minify;
const babelMinify = require("babel-minify");
const CleanCSS = require('clean-css');
const cheerio = require('cheerio');
const crypto = require('crypto');
//ignore数组不读取,copy数组会读取但不做操作仅拷贝
const ignoreArray = ['dirname'];
const copyArray = ['dir', "filename"];
let mode = 'development'
const handleProject = (inputPath, outputPath) => {
outputPath = outputPath + mode;
debugger;
if (fs.existsSync(outputPath)) {
deleteAll(outputPath);
fs.mkdir(outputPath, mkdirErr);
} else {
fs.mkdir(outputPath, mkdirErr)
}
const pathObj = readAllDirSync(inputPath, ignoreArray, copyArray);
const dependencies = {};
for(let i in pathObj["ignore"]){
let oldPath = pathObj["ignore"][i];
let filename = path.join(outputPath, oldPath.slice(inputPath.length+1));
if (mkdirsSync(path.parse(filename).dir)) {
fs.copyFileSync(oldPath, filename);
console.log(oldPath, '->', filename)
}
}
handleDependencies(pathObj, dependencies, outputPath, 'js', inputPath);
handleDependencies(pathObj, dependencies, outputPath, 'css', inputPath);
for (let item in pathObj) {
if (!(/js$|css$|ignore$/.test(item))) {
let jsArray = pathObj[item];
if (/html|htm/.test(item)) {
for (let i in jsArray) {
console.log(jsArray[i], '->', htmlAnalyseScript(jsArray[i], dependencies, outputPath, inputPath));
}
} else {
for (let i in jsArray) {
let filePath = jsArray[i];
let dir = path.parse(filePath).dir;
let sourceDir = dir.slice(inputPath.length + 1);
let fileDir = path.join(outputPath, sourceDir);
let filename = path.join(fileDir, path.parse(filePath).base);
if (mkdirsSync(fileDir)) {
fs.copyFile(filePath, filename, () => {
console.log(filePath, '->', filename)
})
}
}
}
}
}
let outInfo =
"#bundle time:" + getDate();
fs.writeFileSync(outputPath + '/README.md', outInfo);
};
/**
* 根据不同文件类型处理文件
* @param pathObj
* @param dependencies
* @param outputPath
* @param type
* @param inputPath
*/
const handleDependencies = function (pathObj, dependencies, outputPath, type, inputPath) {
let jsArray = pathObj[type];
for (let i in jsArray) {
let scriptPath = fileAnalyser(jsArray[i], outputPath, type, inputPath);
dependencies[type] ? "" : dependencies[type] = {};
dependencies[type][path.parse(jsArray[i]).base] = path.parse(scriptPath).base;
console.log(jsArray[i], '->', scriptPath);
}
};
const getDate = () => {
let time = new Date(),
y = time.getFullYear(),
m = time.getMonth() + 1,
d = time.getDate(),
h = time.getHours(),
mm = time.getMinutes(),
s = time.getSeconds();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " "
+ (h < 10 ? "0" + h : h) + ":" + (mm < 10 ? "0" + mm : mm) + ":" + (s < 10 ? "0" + s : s)
}
;
const mkdirErr = (err) => {
console.error(err)
}
;
/**
* 循环读取相应目录下的文件
* @param filePath
* @param ignoreArray
* @paran copyArray
* @param pathObj
* @returns {*}
*/
const readAllDirSync = (filePath, ignoreArray, copyArray, pathObj) => {
pathObj = pathObj || {};
const ignore = ignoreArray;
let ig = false;
ignore.forEach(item => {
filePath.indexOf(item)>-1 ? ig = true : "";
});
if(!ig){
const files = fs.readdirSync(filePath);
files.forEach(function (ele) {
let info = fs.statSync(path.join(filePath, ele));
if (info.isDirectory()) {
return Object.assign(pathObj, readAllDirSync(path.join(filePath, ele), ignoreArray, copyArray, pathObj));
} else {
let newPath = path.join(filePath, ele);
let ig = false;
ignore.forEach(item => {
newPath.indexOf(item)>-1 ? ig = true : "";
});
if (!ig) {
let cp = false;
copyArray.forEach(item => {
newPath.indexOf(item)>-1 ? cp = true : "";
});
let ext;
if(cp){
ext = "ignore"
}else{
ext = ele.slice(ele.lastIndexOf(".") + 1);
}
pathObj[ext] = pathObj[ext] || [];
pathObj[ext].push(newPath);
}
}
});
}
return pathObj
};
/**
* 修改html文件中的链接地址
* @param filePath
* @param dependencies
* @param dirPath
* @param inputPath
* @returns {string}
*/
const htmlAnalyseScript = (filePath, dependencies, dirPath, inputPath) => {
const content = fs.readFileSync(filePath, 'utf-8');
const $ = cheerio.load(content);
const getScript = $('script');
const scriptDependencies = dependencies['js'];
const cssDependencies = dependencies['css'];
for (let i = 0; i < getScript.length; i++) {
if (getScript[i].attribs.src) {
let pathIndex = getScript[i].attribs.src.lastIndexOf("/") + 1;
let prePath = getScript[i].attribs.src.slice(0, pathIndex);
let scriptPath = getScript[i].attribs.src.slice(pathIndex);
let scriptKey = Object.keys(scriptDependencies);
let scriptIndex = scriptKey.indexOf(scriptPath);
if (scriptIndex > -1) {
$(getScript[i]).attr('src', prePath + scriptDependencies[scriptPath])
// $(getScript[i]).attr('src', scriptDependencies[scriptPath])
}
}
}
const getCSS = $('link');
for (let i = 0; i < getCSS.length; i++) {
if (getCSS[i].attribs.href) {
let pathIndex = getCSS[i].attribs.href.lastIndexOf("/") + 1;
let prePath = getCSS[i].attribs.href.slice(0, pathIndex);
let cssPath = getCSS[i].attribs.href.slice(pathIndex);
let cssKey = Object.keys(cssDependencies);
let cssIndex = cssKey.indexOf(cssPath);
if (cssIndex > -1) {
$(getCSS[i]).attr('href', prePath + cssDependencies[cssPath])
// $(getScript[i]).attr('src', scriptDependencies[scriptPath])
}
}
}
let dir = path.parse(filePath).dir;
let sourceDir = dir.slice(inputPath.length + 1);
let fileDir = path.join(dirPath, sourceDir);
let filename = path.join(fileDir, path.parse(filePath).base);
if (mkdirsSync(fileDir)) {
fs.writeFileSync(filename, minifyHTML($.html(), {
removeComments: true,
collapseWhitespace: true,
minifyCSS: true
}));
return filename
}
};
const getScript = (filename) => {
const content = fs.readFileSync(filename, 'utf-8');
return content
};
/**
* 分析文件并对其进行相应操作
* @param filePath
* @param dirPath
* @param fileType
* @param inputPath
* @returns {string}
*/
const fileAnalyser = (filePath, dirPath, fileType, inputPath) => {
let fileContent = getScript(filePath);
let writeCode;
if (fileType === 'js') {
fileContent = babel.transformSync(fileContent, {
presets: ["@babel/preset-env"]
}).code;
if (mode === 'production') {
const {code} = babelMinify(fileContent, {
mangle: {
keepClassName: true
}
});
writeCode = code;
} else if (mode === 'development') {
writeCode = fileContent;
}
} else if (fileType === 'css') {
if (mode === 'production') {
writeCode = new CleanCSS({}).minify(fileContent).styles;
} else if (mode === 'development') {
writeCode = fileContent;
}
}
let dir = path.parse(filePath).dir;
let sourceDir = dir.slice(inputPath.length + 1);
let nowName = path.parse(filePath).name + '.' + crypto.createHash('md5').update(writeCode).digest('hex') + (fileType === 'js' ? '.js' : '.css');
let fileDir = path.join(dirPath, sourceDir);
let filename = path.join(fileDir, nowName);
if (mkdirsSync(fileDir)) {
fs.writeFileSync(filename, writeCode);
return filename
}
}
;
/**
* 循环创建目录
* @param dirname
* @returns {boolean}
*/
const mkdirsSync = (dirname) => {
if (fs.existsSync(dirname)) {
return true;
} else {
if (mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname);
return true;
}
}
}
;
/**
* 循环删除目录及文件
* @param path
*/
const deleteAll = (path) => {
let files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function (file) {
let curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) { // recurse
deleteAll(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
/**
* 循环拷贝目录及文件
* @param path
*/
const copyAll = (inputPath, outputPath) => {
if (fs.statSync(inputPath).isDirectory()) {
let files = [];
if (fs.existsSync(inputPath)) {
files = fs.readdirSync(inputPath);
files.forEach(function (file) {
let curPath = path.join(inputPath, file);
if (fs.statSync(curPath).isDirectory()) { // recurse
copyAll(curPath, outputPath);
} else {
let filename = path.join(outputPath, curPath.slice(curPath.indexOf("\\")));
if (mkdirsSync(path.parse(filename).dir)) {
fs.copyFileSync(curPath, filename);
console.log(curPath, '->', filename)
}
}
});
}
} else {
let filename = path.join(outputPath, inputPath.slice(inputPath.indexOf("\\")));
if (mkdirsSync(path.parse(filename).dir)) {
fs.copyFileSync(inputPath, filename);
console.log(inputPath, '->', filename)
}
}
};
if (global.process.argv[2]) {
mode = global.process.argv[2];
}
handleProject('./my_source', './my_');