This repository has been archived by the owner on Apr 14, 2022. It is now read-only.
forked from zouhir/lqip-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (72 loc) · 2.42 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
var loaderUtils = require("loader-utils");
// lqip: https://github.com/zouhir/lqip / https://github.com/memrise/lqip
var lqip = require("@memrise/lqip");
module.exports = function (contentBuffer) {
this.cacheable && this.cacheable();
var callback = this.async();
var content = contentBuffer.toString("utf8");
// image file path
var path = this.resourcePath;
// user options
var config = loaderUtils.getOptions(this) || {};
config.base64 = "base64" in config ? config.base64 : true;
config.palette = "palette" in config ? config.palette : false;
var contentIsUrlExport = /^module.exports = "data:(.*)base64,(.*)/.test(
content
);
var contentIsFileExport = /^module.exports = (.*)/.test(content);
var source = "";
if (contentIsUrlExport) {
source = content.match(/^module.exports = (.*)/)[1];
} else {
if (!contentIsFileExport) {
var fileLoader = require("file-loader");
content = fileLoader.call(this, contentBuffer);
}
source = content.match(/^module.exports = (.*);/)[1];
}
// promise array in case users want both
// base64 & color palettes generated
// that means we have 2 promises to resolve
var outputPromises = [];
if (config.base64 === true) {
outputPromises.push(lqip.base64(path));
} else {
// push null if the user did not wish to use Base64 to preserve the order
outputPromises.push(null);
}
// color palette generation is set to false by default
// since it is little bit slower than base64 generation
// if users wants it, grab it!
if (config.palette === true) {
outputPromises.push(lqip.palette(path));
} else {
// push null if the user did not wish to use palette to preserve the order
outputPromises.push(null);
}
// final step, resolving all the promises we got so far
Promise.all(outputPromises)
.then((data) => {
if (data) {
var result = 'module.exports = { "src": ' + source;
// either null or base64
if (data[0]) {
result += ', "preSrc": ' + JSON.stringify(data[0]);
}
// either null or palette
if (data[1]) {
result += ', "palette": ' + JSON.stringify(data[1]);
}
result += " };";
// the output will be sent to webpack!
callback(null, result);
} else {
callback(err, null);
}
})
.catch((error) => {
console.error(error);
callback(err, null);
});
};
module.exports.raw = true;