起因
写微信小程序的人大概都知道,微信小程序对包有大小限制,所以资源的压缩还是很有必要的。因为之前都是通过 TinyPNG 网站手工进行压缩,还是有点麻烦的,偶然发现 TinyPNG 有相关 API 提供,于是写了脚本将这件事自动化,提升效率。
功能
- 压缩文件夹内所有图片。
- 将压缩过的图片路径记录,防止二次压缩。
- 可以添加文件后缀列表,只压缩该后缀的图片文件。
- 添加排除文件名列表,不压缩该文件。
代码介绍
配置介绍
const config = {
/** key 值在官网可以获取 */
key: '',
/** 需要遍历的文件夹路径 */
path: './src',
/** 标志存放位置 */
idPath: './src/idPath.json',
/** 文件扩展名,只有以下文件会进行压缩 */
ext: ['png', 'jpeg', 'jpg'],
/** 排除文件名,以下文件名不进行压缩 */
exclude: []
}
获取 key
赋值 key
tinify.key = config.key
获取已压缩图片文件所有路径
let alreadyDoneList = []
if (fs.existsSync(config.idPath)) {
alreadyDoneList = fs.readJSONSync(config.idPath)
}
遍历文件夹获取所有图片文件
const getAllImages = async srcPath => {
const fileList = []
const findPath = path => {
const files = fs.readdirSync(path)
files.forEach(item => {
let fPath = join(path, item)
let status = fs.statSync(fPath)
if (status.isDirectory()) {
findPath(fPath)
}
if (status.isFile()) {
const ext = item.split('.')[item.split('.').length - 1]
// 判断该文件是否被压缩过
if (config.ext.includes(ext) && !alreadyDoneList.includes(fPath)) {
fileList.push(fPath)
}
}
})
}
findPath(srcPath)
return fileList
}
压缩图片
const zipImage = (path, writeIdPath) => {
fs.readFile(path, (err, sourceData) => {
if (err) {
throw err
}
console.log(path, '文件读取成功')
tinify.fromBuffer(sourceData).toBuffer((err, resultData) => {
if (err) {
throw err
}
console.log(path, '压缩成功')
fs.writeFile(path, resultData, (err => {
if (err) {
throw err
}
alreadyDoneList.push(path)
writeIdPath()
console.log(path, '写入成功')
}))
})
})
}
写入标记文件
const writeIdPath = () => {
fs.writeFile(config.idPath, JSON.stringify(alreadyDoneList), (err) => {
if (err) {
throw err
}
})
}
循环执行压缩
getAllImages(config.path).then(fileList => {
fileList.forEach(item => zipImage(item, writeIdPath))
})