forked from nickzou/laravel-mix-image-resizer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
97 lines (88 loc) · 2.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const mix = require('laravel-mix')
const fs = require('fs-extra')
const path = require('path')
const glob = require('glob')
const sharp = require('sharp')
const imageSize = require('image-size')
const imagemin = require('imagemin')
const imageminMozjpeg = require('imagemin-mozjpeg')
const imageminPngquant = require('imagemin-pngquant')
const imageminWebp = require('imagemin-webp')
const defaultOptions = {
disable: false,
from: 'resources',
to: 'public',
sizes: [
414,
768,
828,
1024,
1280,
1536,
1600
],
webp: true,
imageminMozjpegOptions: {
quality: 80
},
imageminPngquantOptions: {
quality: [0.3, 0.5]
},
imageminWebpOptions: {
quality: 50
},
}
class ImageResizer {
register(extraOptions = {}) {
const {
disable,
sizes,
from,
to,
webp,
imageminMozjpegOptions,
imageminPngquantOptions,
imageminWebpOptions,
} = Object.assign(defaultOptions, extraOptions)
if (disable) return
sizes.sort((a, b) => {
if (a > b) {
return 1
} else {
return -1
}
})
fs.copySync(from, to)
const images = glob.sync(to + '/**/*').forEach((imagePath) => {
if (imagePath.match(/\.(jpe?g|png|gif)$/i) === null || imagePath.match('resized')) {
return
}
let {root, dir, base, ext, name} = path.parse(imagePath)
imagemin([imagePath, dir + '/' + name + '-resized-*'], {
destination: dir,
plugins: [
imageminMozjpeg(imageminMozjpegOptions),
imageminPngquant(imageminPngquantOptions),
],
})
if (webp) {
imagemin([imagePath, dir + '/' + name + '-resized-*'], {
destination: dir,
plugins: [
imageminWebp(imageminWebpOptions)
],
})
}
let width = imageSize(imagePath).width
sizes.forEach((w) => {
if (width < w) {
return
}
sharp(imagePath)
.resize(w)
.toFile(dir + '/' + name + '-resized-' + w + ext)
})
})
}
}
mix.extend('ImageResizer', new ImageResizer())