gulp 批量压缩图片

2018-9-7 15:15:58 人评论 次浏览 分类:行内元素

const fs = require('fs');
const path = require('path');
const tinify = require("tinify");
tinify.key = "xxx";

gulp.task('compress-images', function(){
	var fileDisplay = function (filePath){
	    fs.readdir(filePath,function(err,files){
	        if(err){
	            console.warn(err);
	        }else{
	            files.forEach(function(filename){
	                var filedir = path.join(filePath,filename);
	                fs.stat(filedir,function(eror,stats){
	                    if(eror){
	                        console.warn('get file stats error!');
	                    }else{
	                        var isFile = stats.isFile();
	                        var isDir = stats.isDirectory();
	                        var relativeDir = filedir.replace(__dirname, '');
	                        if(isFile){
	                            files.forEach(function(fileName){
									var source = tinify.fromFile(filedir);
									source.toFile(`${__dirname}\\build${relativeDir}`);
								});
	                        }
	                        if(isDir){
	                        	fs.mkdirSync(`${__dirname}\\build${relativeDir}`);
	                            fileDisplay(filedir);
	                        }
	                    }
	                });
	            });
	        }
	    });
	}
	
	fileDisplay(path.resolve(__dirname, 'images'));
});

% tinify 需要申请key  %

共有访客发表了评论 网友评论

验证码: 看不清楚?