1. 安装nodejs
2. 安装cssmin。 npm install cssmin -g
3. 安装yuicompressor。npm install yuicompressor -g
4. 设置NODE_PATH到全局C:\Users\Administrator\AppData\Roaming\npm\node_modules (默认nodejs全局目录)
5. 创建source目录,创建dist目录
6. 创建compress.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
|
var
fs = require(
'fs'
);
var
cssmin = require(
'cssmin'
);
var
compressor = require(
'yuicompressor'
);
var
sourceDir =
"source"
;
var
distDir =
"dist"
;
var
fileNames = fs.readdirSync(sourceDir);
var
fileIndex = 0;
compressFile(fileNames[fileIndex]);
function
compressFile(fileName){
if
(fileName==
null
){
return
;
}
var
sourceFileName = fileName;
var
sourceFilePath = sourceDir+
"/"
+sourceFileName;
var
suffix = getSuffix(fileName);
if
(suffix==
"css"
){
compressCssFile(fileName);
return
;
}
else
if
(suffix==
"js"
){
compressJsFile(fileName);
return
}
compressFile(fileNames[++fileIndex]);
}
function
compressCssFile(fileName){
var
sourceFileName = fileName;
var
sourceFilePath = sourceDir+
"/"
+sourceFileName;
var
compressedFileName = sourceFileName.replace(
".css"
,
""
)+
".min.css"
;
var
compressedFilePath = distDir+
"/"
+sourceFileName;
var
css = fs.readFileSync(sourceFilePath, encoding=
'utf8'
);
var
min = cssmin(css);
fs.writeFile(compressedFilePath,min,
function
(err){
if
(err==
null
){
console.log(
"compress file["
+sourceFileName+
"] to file["
+compressedFileName+
"] successfully ..."
);
compressFile(fileNames[++fileIndex]);
}
else
{
console.log(
"encounter error : "
+err);
}
});
}
function
compressJsFile(fileName){
var
sourceFileName = fileName;
var
sourceFilePath = sourceDir+
"/"
+sourceFileName;
var
compressedFileName = sourceFileName.replace(
".js"
,
""
)+
".min.js"
;
var
compressedFilePath = distDir+
"/"
+compressedFileName;
compressor.compress(sourceFilePath, {
charset:
'utf8'
,
type:
'js'
,
nomunge:
true
,
'line-break'
: 80
},
function
(err, data, extra) {
fs.writeFile(compressedFilePath,data,
function
(err){
if
(err==
null
){
console.log(
"compress file["
+sourceFileName+
"] to file["
+compressedFileName+
"] successfully ..."
);
compressFile(fileNames[++fileIndex]);
}
else
{
console.log(
"encounter error : "
+err);
}
});
});
}
function
getSuffix(fileName){
var
index = fileName.lastIndexOf(
"."
);
return
fileName.substring(index+1);
}
|
7. 将要要所的文件放入source目录,执行compress.js(命令node compress),将文件压缩至dist目录。
版权声明:原创作品,如需转载,请注明出处。否则将追究法律责任
本文转自 antlove 51CTO博客,原文链接:http://blog.51cto.com/antlove/1723130