vue 中配置图片压缩 (tinify)

配置原则:压缩后的图片替换原图片

安装依赖

npm install glob --save-dev
npm install tinify --save-dev

项目根目录创建配置文件 .tinify.config

entry = dist/**/*.?(jpg|png)
key = you tinify key

获取配置文件信息

const _config = glob.sync('.tinify.config')
const _configFile = _config && _config[0]

if (!_configFile) {
  console.log(chalk.red('please build the .tinify.config file in this project.'))
  return false
}

获取所有要压缩的图片

config.entries.forEach((entry) => {
  const res = glob.sync(entry)

  if (Object.prototype.toString.call(res).slice(8, -1).toLowerCase() === 'array') {
    files = files.concat(res)
  } else {
    files = files.concat([res])
  }
})

tinify.js 脚本

node tinify.js
const fs = require('fs')
const glob = require('glob')
const tinify = require('tinify')
const inquirer = require('inquirer')
const chalk = require('chalk')

const _config = glob.sync('.tinify.config')
const _configFile = _config && _config[0]

if (!_configFile) {
  console.log(chalk.red('please build the .tinify.config file in this project.'))
  return false
}

const configContents = fs.readFileSync(_configFile, {
  encoding: 'utf8'
})

const param = function (key, contents) {
  const reg = new RegExp(`${key}\\s*=\\s*(\\S+)\\s*`, 'g')
  const data = []

  if (contents.match(reg)) {
    contents.match(reg).forEach((item) => {
      const _reg = new RegExp(`${key}\\s*=\\s*(\\S+)\\s*`)

      data.push(item.match(_reg) && item.match(_reg)[1])
    })
  }

  return data
}

/**
 * 压缩替换文件
 * @param {Array} files 所有要压缩的文件
 * @param {Number} fileIndex 当前要要压缩的文件的索引
 * @param {Number} keyIndex 当前使用的key的索引
 */
const transform = function (files, fileIndex = 0, keyIndex = 0) {
  if (!config.keys[keyIndex] || fileIndex >= files.length) return false

  const file = files[fileIndex]
  const timeStamp = new Date().getTime()
  tinify.key = config.keys[keyIndex]

  tinify.fromFile(file).toFile(file).then(() => {
    console.log(chalk.green(`${file}: transform success (${new Date().getTime() - timeStamp}ms)`))
    transform(files, fileIndex + 1, keyIndex)
  }).catch((error) => {
    if (error instanceof tinify.AccountError) {
      console.log(chalk.yellow(`${file}: change another key retransform.`))
      transform(files, fileIndex, keyIndex + 1)
    } else {
      console.log(chalk.red(`${file}: ${error}`))
    }
  })
}

const config = {
  keys: param('key', configContents),
  entries: param('entry', configContents)
}

if (config.entries.length < 1) return

let files = []

// 获取所有要压缩的文件
config.entries.forEach((entry) => {
  const res = glob.sync(entry)

  if (Object.prototype.toString.call(res).slice(8, -1).toLowerCase() === 'array') {
    files = files.concat(res)
  } else {
    files = files.concat([res])
  }
})

inquirerName = 'choose files'

inquirer.prompt({
  type: 'checkbox',
  name: inquirerName,
  choices: Array.from(new Set(files)),
  default: Array.from(new Set(files))
}).then((res) => {
  // 开始压缩文件
  transform(res[inquirerName])
})

你可能感兴趣的:(vue 中配置图片压缩 (tinify))