-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimages.11ty.js
116 lines (105 loc) · 2.82 KB
/
images.11ty.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const path = require('node:path')
const {glob} = require('glob')
const sharp = require('sharp')
const mkdirp = require('mkdirp')
const outputPath = '_site/assets/images/'
const resizeConf = {
sizes: [
{
width: 320,
rename: { suffix: '-320w' },
},
{
width: 640,
rename: { suffix: '-640w' },
},
{
width: 1280,
rename: { suffix: '-1280w' },
},
{
width: 1920,
rename: { suffix: '-1920w' },
},
{
width: 3840,
rename: { suffix: '-3840w' },
},
],
jpegOptions: {
quality: 80,
progressive: true,
withMetadata: true,
force: false,
// ErrorOnUnusedImage: false,
// errorOnEnlargement: false
},
webpOptions: {
quality: 80,
withMetadata: true,
force: true,
},
pngOptions: {
compressionLevel: 8,
force: false,
},
}
module.exports = class {
async data() {
const filePath = path.join(__dirname, '/images/')
return {
permalink: '/assets/images/images.json',
eleventyExcludeFromCollections: true,
filePath,
}
}
async loadImages(imgFolder) {
const cwd = path.resolve(imgFolder.file)
const getImages = glob
const processedImages = []
const imgs = await getImages('**/*(*.jpg|*.png|*.gif)', { cwd })
const imgsRendered = await getImages('**/*(*.jpg|*.png|*.gif)', { cwd: outputPath })
for (const img of imgs) {
const ext = path.extname(img)
const base = path.basename(img, ext)
const dir = path.dirname(img)
mkdirp.sync(path.join(outputPath, dir))
if (imgsRendered.includes(img)) {
// Console.log(`FOUND MASTER FOR ${img}`)
} else {
// Console.log(`PASS THROUGH MASTER FOR ${img}`)
const passThroughImg = sharp(imgFolder.file + img)
passThroughImg.toFile(path.join(outputPath, dir, base + ext))
}
const image = sharp(imgFolder.file + img)
image
.jpeg(resizeConf.jpegOptions)
.png(resizeConf.pngOptions)
.webp(resizeConf.webpOptions)
for (const size of resizeConf.sizes) {
const newPath = path.join(dir, base + size.rename.suffix + ext)
const newPathOutput = path.join(outputPath, newPath)
if (imgsRendered.includes(newPath)) {
// Console.log(`FOUND RESIZED IMAGE FOR ${newPath}`)
continue
}
// Console.log(`RENDERING NEW RESIZED IMAGE FOR ${newPath}`)
const resized = image.resize({
width: size.width,
withoutEnlargement: true,
kernel: 'lanczos2',
})
resized.toFile(newPathOutput)
}
processedImages.push(img)
}
return JSON.stringify(processedImages, null, '\t')
}
async render({ filePath }) {
try {
return await this.loadImages({ file: filePath })
} catch (error) {
throw new Error(error)
}
}
}