-
Notifications
You must be signed in to change notification settings - Fork 5
/
loader.resize.js
243 lines (212 loc) · 8.67 KB
/
loader.resize.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const os = require('node:os');
const fs = require('node:fs');
const sharp = require('sharp');
const path = require('node:path');
const loaderUtils = require('loader-utils');
const urlLoader = require('url-loader');
const fileLoader = require('file-loader');
const deepMerge = require('lodash.merge');
const weblog = require('webpack-log');
const createHash = require('webpack/lib/util/createHash');
const logger = weblog({ name: 'loader-resize' });
const imageminConfig = require('./imagemin.config');
const { version: sharpVersion } = require('sharp/package.json');
const imageminConfigModule = require.resolve('./imagemin.config');
const UTILS = require('./webpack.utils');
const DEFAULT_OPTIONS = {
cacheDirectory: false,
verbose: false,
};
const DEFAULT_FIT = 'inside';
const ALLOWED_PATTERN = /\.(jpeg|jpg|png|gif)(\?.*)?$/i;
module.exports = async function ResizeLoader(content) {
const loaderContext = this;
if (loaderContext.cacheable) loaderContext.cacheable();
const loaderCallback = loaderContext.async();
loaderContext.addDependency(loaderContext.resourcePath);
loaderContext.addDependency(imageminConfigModule);
const query = loaderContext.resourceQuery
? Object.fromEntries(new URLSearchParams(loaderContext.resourceQuery.slice(1)).entries())
: {};
const options = deepMerge({}, DEFAULT_OPTIONS, loaderContext.getOptions());
const context = options.context || loaderContext.rootContext;
const { cacheDirectory } = options;
delete options.cacheDirectory;
if (cacheDirectory) {
if (!fs.existsSync(cacheDirectory)) {
fs.mkdirSync(cacheDirectory, { recursive: true });
}
}
const nextLoader = query.inline === 'inline' ? urlLoader : fileLoader;
if (!('resize' in query)) {
return loaderCallback(null, nextLoader.call(loaderContext, content));
}
if (!ALLOWED_PATTERN.test(loaderContext.resourcePath)) {
const errorMessage = `Resize not allowed for: ${JSON.stringify(loaderContext.resourcePath)}.`;
loaderContext.emitError(errorMessage);
loaderCallback(errorMessage);
throw new Error(errorMessage);
}
if ('inline' in query) {
delete query.inline;
}
const resourceInfo = path.parse(loaderContext.resourcePath);
const resourceFormat = resourceInfo.ext.slice(1).toLowerCase();
const relativePath = UTILS.slash(path.relative(__dirname, loaderContext.resourcePath));
const resizeMatch = query.resize.trim().match(/^(\d*)(x(\d*))?(\w+)?$/) || [];
const resizeWidth = parseInt(resizeMatch[1], 10);
const resizeHeight = parseInt(resizeMatch[2], 10);
const resizeFit = (resizeMatch[4] || DEFAULT_FIT).trim();
if (!query.resize && !query.name) {
query.name = path.basename(loaderContext.resourcePath, path.extname(loaderContext.resourcePath));
}
const format = (query.format || resourceFormat).toLowerCase();
const name =
((query.name
? loaderUtils.interpolateName(loaderContext, query.name, {
context,
content,
})
: null) ||
`${resourceInfo.name}@resize-${resizeWidth || ''}x${resizeHeight || ''}${
resizeFit && resizeFit !== DEFAULT_FIT ? `-${resizeFit}` : ''
}`) + (query.suffix ? `-${query.suffix}` : '');
const resourceHash = createHash('xxhash64')
.update(sharpVersion + content)
.digest('hex');
const formatConfig = imageminConfig[format] || {};
const cacheFilename = `${encodeURIComponent(`${relativePath}?${JSON.stringify(query)}`)}.json`;
const cacheFilepath = cacheDirectory ? path.join(cacheDirectory, cacheFilename) : undefined;
let cacheData;
if (cacheFilepath && fs.existsSync(cacheFilepath)) {
try {
cacheData = JSON.parse(fs.readFileSync(cacheFilepath).toString());
} catch (cacheError) {
logger.error(`error cache '${relativePath}${loaderContext.resourceQuery}'`, cacheError);
cacheData = undefined;
}
}
if (
cacheData !== undefined &&
cacheData.type === 'Buffer' &&
cacheData.data &&
cacheData.hash === resourceHash &&
cacheData.config === JSON.stringify(formatConfig)
) {
if (options.verbose) {
logger.info(`load cache '${relativePath}${loaderContext.resourceQuery}'`);
}
loaderContext.resourcePath = path.join(resourceInfo.dir, `${name}.${format}`);
return loaderCallback(null, nextLoader.call(loaderContext, Buffer.from(cacheData.data, 'base64')));
}
const resourceImage = sharp(content);
const resourceMeta = await resourceImage.metadata();
const resizeOptions = {
fit: resizeFit,
withoutEnlargement: true,
};
if (query.resizeOptions) {
Object.assign(resizeOptions, query.resizeOptions);
}
const formatOptions = {};
const quality = query.quality ? parseInt(query.quality, 10) : 0;
if (quality > 0) {
formatOptions.quality = quality;
}
const lossless = typeof query.lossless !== 'undefined' ? !!query.lossless : resourceFormat === 'png';
if (format === 'webp') {
if (lossless || quality === 100) {
formatOptions.lossless = true;
} else if (!quality) {
formatOptions.quality = imageminConfig.webp.quality;
}
if (imageminConfig.webp.options) {
Object.assign(formatOptions, imageminConfig.webp.options);
}
if (query.options) {
Object.assign(formatOptions, query.options);
}
}
if (format === 'avif') {
if (lossless) {
formatOptions.lossless = true;
} else if (!quality) {
formatOptions.quality = imageminConfig.avif.quality;
}
if (imageminConfig.avif.options) {
Object.assign(formatOptions, imageminConfig.avif.options);
}
if (query.options) {
Object.assign(formatOptions, query.options);
}
}
if (format === 'jpg' || format === 'jpeg') {
if (!quality) {
formatOptions.quality = imageminConfig.jpeg.quality;
}
if (imageminConfig.jpeg.options) {
Object.assign(formatOptions, imageminConfig.jpeg.options);
}
if (query.options) {
Object.assign(formatOptions, query.options);
}
}
if (format === 'png') {
if (!quality) {
formatOptions.quality = imageminConfig.png.quality;
}
if (imageminConfig.png.options) {
Object.assign(formatOptions, imageminConfig.png.options);
}
if (query.options) {
Object.assign(formatOptions, query.options);
}
}
if (resizeWidth || resizeHeight) {
resourceImage.resize(resizeWidth || resourceMeta.width, resizeHeight || resourceMeta.height, resizeOptions);
}
resourceImage.toFormat(format.toLowerCase(), formatOptions);
let resizeLimit = (callback) => callback();
if (loaderContext.resizeLimit) {
resizeLimit = loaderContext.resizeLimit;
} else {
const { default: pLimit } = await import('p-limit');
loaderContext.resizeLimit = pLimit(os.cpus().length - 1);
}
await resizeLimit(async () => {
const resizePromise = await new Promise((resizeResolve, resizeReject) => {
resourceImage
.toBuffer()
.then((buffer) => {
if (cacheFilepath) {
fs.writeFileSync(
cacheFilepath,
JSON.stringify({
type: 'Buffer',
data: buffer.toString('base64'),
hash: resourceHash,
config: JSON.stringify(formatConfig),
})
);
}
if (options.verbose) {
logger.info(`save cache '${relativePath}${loaderContext.resourceQuery}'`);
}
resizeResolve(buffer);
loaderContext.resourcePath = path.join(resourceInfo.dir, `${name}.${format}`);
loaderCallback(null, nextLoader.call(loaderContext, buffer));
return buffer;
})
.catch((bufferError) => {
loaderContext.emitError(bufferError);
loaderCallback(bufferError);
resizeReject(bufferError);
});
}).catch((promiseError) => {
loaderContext.emitError(promiseError);
loaderCallback(promiseError);
});
return resizePromise;
});
};
module.exports.raw = true;