-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (65 loc) · 1.81 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
const replaceExt = require('replace-ext');
function getImagePath(value) {
let path = false;
if (value.indexOf('data:') === -1 && value.indexOf('var(') === -1) {
const reg = /(?:\(['"]?)(.*?)(?:['"]?\))/;
const cleanPath = reg.exec(value);
if (cleanPath !== null) {
path = cleanPath[1];
}
}
return path;
}
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
}
function localReplaceExt(value, ext) {
let newValue;
if (isValidHttpUrl(value)) {
const url = new URL(value);
url.pathname = replaceExt(url.pathname, ext);
newValue = url;
} else {
newValue = replaceExt(value, ext);
}
return newValue;
}
module.exports = (opts = { }) => {
const useAvif = opts && typeof opts.useAvif !== 'undefined' ? opts.useAvif : true;
const useWebp = opts && typeof opts.useWebp !== 'undefined' ? opts.useWebp : true;
return {
postcssPlugin: 'imageset-type',
Declaration: {
'background-image': (decl) => {
if (decl.value.includes('image-set')) {
return;
}
const imagePath = getImagePath(decl.value);
if (imagePath === false) {
return;
}
let imageSet = [];
if (useAvif) {
imageSet.push(`'${localReplaceExt(imagePath, '.avif')}' type('image/avif')`);
}
if (useWebp) {
imageSet.push(`'${localReplaceExt(imagePath, '.webp')}' type('image/webp')`);
}
if (useAvif || useWebp) {
imageSet.push(`'${imagePath}' type('image/jpeg')`);
decl.after({
prop: 'background-image',
value: `image-set(${imageSet.join(',')})`,
});
}
}
}
}
}
module.exports.postcss = true