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
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目录。