loading...

1

前端文件压缩

javascript读完大概需要18分钟

  • 发布时间:2017-11-12 13:00 星期日
  • 刘伟波
  • 252
  • 更新于2017-12-18 18:05 星期一

一 node-minify 压缩前端js

https://www.npmjs.com/package/node-minify

npm install node-minify                                ./js/admin*.js',  './**/*.js',

var compressor = require('node-minify');

// Using Google Closure Compiler
compressor.minify({
compressor: 'gcc',
input: 'foo.js',
output: 'bar.js',
callback: function (err, min) {}
});

// Using UglifyJS
compressor.minify({
compressor: 'uglifyjs',
input: './**/*.js',
output: 'bar.js',
callback: function (err, min) {}
});

// Using Promise
var promise = compressor.minify({
compressor: 'uglifyjs',
input: './**/*.js',
output: 'bar.js'
});

promise.then(function(min) {});


批量处理,css同理

var compressor = require('node-minify');
var obj=[
{
test:['./js/adminVideoShow.js','./js/adminUpdateArticle.js'],
output:'a.min.js'
},{
test:['./js/common.js','./js/comment.js'],
output:'b.min.js'
}
];
for(let i in obj){
compressor.minify({
compressor: 'gcc', // 'clean-css'
input: obj[i].test,
output: obj[i].output,
callback: function (err, min) {}
});
}


批量对应js=>min.js配合node文件操作

let fs = require('fs');
let join = require('path').join;
let paths = require('path');
var compressor = require('node-minify');

/**
*
* @param startPath 起始目录文件夹路径
* @returns {Array}
*/
function findSync(startPath) {
let result = [];

function finder(path) {
let files = fs.readdirSync(path);
files.forEach((val, index) => {
let fPath = join(path, val);
let stats = fs.statSync(fPath);
if (stats.isDirectory()) finder(fPath);
if (stats.isFile()) {
// console.log('fPath',paths.basename(fPath,'.js'));
console.log(fPath);
compressor.minify({
compressor: 'gcc',
input: fPath,
output: './js/min/' + paths.basename(fPath,'.js') + '.min.js',
callback: function (err, min) {
}
});
// result.push(fPath)
result.push(paths.basename(fPath,'.js'))
}
});

}

finder(startPath);
return result;
}

let fileNames = findSync('./js');



增加哈希值后缀

参数似乎不管用 https://www.npmjs.com/package/hash-rename-file

var hrf = require('hash-rename-file');
var opt = {
base: 'res', // destPath retain src dir info
type: 'tp', // file type, support ('tp', 'fnt', 'spine', 'normal'), default: 'normal'
num: 4 // append hash bit num to filename, such as: filename_1234567.png
};
hrf('./css/a.css', './css/hash/', function (err) {
if (err) {
console.error(err);
}
});


压缩js并替换js文件增加哈希值

let fs = require('fs');
let join = require('path').join;
let paths = require('path');
var compressor = require('node-minify');

/**
*
* @param startPath 起始目录文件夹路径
* @returns {Array}
*/
// 寻找js并压缩
function findSync(startPath) {
function finder(_path) {
let files = fs.readdirSync(_path);
files.forEach((val, index) => {
let fPath = join(_path, val);
let stats = fs.statSync(fPath);
console.log(fPath+'文件正在压缩...');
if(!/min/.test(paths.dirname(fPath))){
if (stats.isDirectory()) finder(fPath);
if (stats.isFile()) {
// console.log('fPath',paths.basename(fPath,'.js'));
// console.log(fPath);
// compressor.minify({
// compressor: 'gcc',
// input: fPath,
// output: './js/min/' + paths.basename(fPath,'.js') + Math.random()+'.min.js',
// callback: function (err, min) {
// }
// });
}
}


});

}
finder(startPath);
}
// 寻找php文件并替换
function findSyncChange(startPath) {
function finder(_path) {
let files = fs.readdirSync(_path);
files.forEach((val, index) => {
let fPath = join(_path, val);
let stats = fs.statSync(fPath);

if (stats.isFile()) {
let reg=/<script[ ]+src="(\.\/)?js\/.*><\/script>/ig;
if(paths.extname(fPath)==='.php'){
console.log(fPath+'正在替换...');
fs.readFile(fPath,(err,data)=>{
let result=data.toString().replace(reg, function (str) {
let str2=str.replace('</script>',''); // 去除后缀
let basename=str.replace('</script>','').substring(str2.lastIndexOf('/')+1,str2.lastIndexOf('.js')); // admin common
if(/\/min\//.test(str2)){
return str.replace(basename,basename+'.111');
}else {

return str.replace(basename,'min/'+basename+'.222.min');
}
});

fs.writeFile('test2-'+fPath,result,(err,data)=>{
console.log(err);
})
});
}

}

});

}
finder(startPath);
}

findSync('./js');
// findSyncChange('./');



二 Gruntfile.js

module.exports = function(grunt){
//初始化grunt 配置
grunt.initConfig({

//获取package.json的信息
pkg: grunt.file.readJSON('package.json'),
//concat插件的配置信息
concat: {
options:{
stripBanners:true, //合并时允许输出头部信息
banner:'/*!<%= pkg.name %> - <%= pkg.version %>-'+'<%=grunt.template.today("yyyy-mm-dd") %> */'
},
cssConcat:{
src:['src/css/css1.css','src/css/css2.css'],
dest:'src/css/concat/<%= pkg.name %> - <%= pkg.version %>.css' //dest 是目的地输出
},
jsConcat:{
src:'src/js/*.js',
dest:'src/js/concat/<%=pkg.name %> - <%= pkg.version %>.js'
}
},
//压缩css
cssmin:{
options:{
stripBanners:true, //合并时允许输出头部信息
banner:'/*!<%= pkg.name %> - <%= pkg.version %>-'+'<%=grunt.template.today("yyyy-mm-dd") %> */\n'
},
build:{
src:'src/css/concat/<%=pkg.name %> - <%=pkg.version %>.css',//压缩是要压缩合并了的
dest:'dist/css/<%= pkg.name %> - <%= pkg.version %>.min.css' //dest 是目的地输出
}
},
//压缩js
uglify:{
options:{
stripBanners:true, //合并时允许输出头部信息
banner:'/*!<%= pkg.name %> - <%= pkg.version %>-'+'<%=grunt.template.today("yyyy-mm-dd") %> */\n'
},
build:{
src:'src/js/concat/<%=pkg.name %> - <%=pkg.version %>.js',//压缩是要压缩合并了的
dest:'dist/js/<%= pkg.name %> - <%= pkg.version %>.min.js' //dest 是目的地输出
}
},

jshint:{
options:{
jshintrc:'.jshint'
},
build:['Gruntfile.js','src/js/*js']
},

csslint:{
options:{
csslintrc:'.csslint'
},
build:['src/css/*.css']

},
//watch自动化
watch:{
build:{
files:['src/js/*.js','src/css/*.css'],
tasks:['jshint','csslint','concat','cssmin','uglify'],
options:{spawn:false}
}
}

});
//告诉grunt我们将使用插件
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-watch');
//告诉grunt当我们在终端输入grunt时需要做些什么
grunt.registerInitTask('default',['jshint','csslint','concat','cssmin','uglify','watch']);//先进行语法检查,如果没有问题,再合并,再压缩
};


package.json

{
"name": "demo",
"file": "zepto",
"version": "0.1.0",
"description": "demo",
"license": "MIT",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-clean": "~0.5.0",
"grunt-contrib-concat": "~0.5.0",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-csslint": "^2.0.0",
"grunt-contrib-cssmin": "^2.2.1",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-requirejs": "~0.4.1",
"grunt-contrib-uglify": "~0.2.1",
"grunt-contrib-watch": "^1.0.0",
"grunt-strip": "~0.2.1"
},
"dependencies": {
"express": "3.x",
"grunt-css": "^0.5.4"
}
}


.csslint


{
"adjoining-classes":false,
"box-sizing":false,
"box-model" : false,
"compatible-vendor-prefixes": false,
"floats":false,
"font-sizes":false,
"gradients":false,
"important":false,
"known-properties":false,
"outline-none":false,
"qualified-headings":false,
"regex-selectors":false,
"shorthand":false,
"text-indent":false,
"unique-headings":false,
"universal-selector":false,
"unqualified-attributes":false
}


.jshint

{
"boss":false,
"curly":true,
"eqeqeq":true,
"expr":true,
"immed":true,
"newcap":true,
"noempty":true,
"noarg":true,
"undef":true,
"regexp":true,

"browser":true,
"devel":true,
"node":true
}



node.js对文件压缩


html-minifier 对html中的css进行压缩

clean-css对css进行压缩

uglifyjs2对js进行压缩



图片优化

png8  256  每一个像素8比特   支持透明

png24  2^24  每一个像素24比特    不支持透明

png32  2^32     每一个像素32比特    支持透明


文件大小  色彩丰富程度

针对不同的场景选择不同的图片格式

比如,蓝天 大海  选择png8就足够

 










你可能感兴趣的文章

    发表评论

    评论支持markdown,评论内容不能超过500字符,如果内容过多或者要及时回复,建议去 平台,一般一天之内就会回复。
    关于技术问题或者有啥不懂的都可以留言,我会定期回复答 疑,推荐最新仓库 前端知识体系, 感謝支持!