Skip to content

Commit accb414

Browse files
refactor: code
1 parent 81bf601 commit accb414

File tree

4 files changed

+110
-134
lines changed

4 files changed

+110
-134
lines changed

src/Webpack4Cache.js

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ export default class Webpack4Cache {
1717
return findCacheDir({ name: 'compression-webpack-plugin' }) || os.tmpdir();
1818
}
1919

20-
async get(task, sources) {
21-
const weakOutput = this.weakCache.get(task.assetSource);
20+
async get(cacheData, sources) {
21+
const weakOutput = this.weakCache.get(cacheData.source);
2222

2323
if (weakOutput) {
2424
return weakOutput;
@@ -30,12 +30,13 @@ export default class Webpack4Cache {
3030
}
3131

3232
// eslint-disable-next-line no-param-reassign
33-
task.cacheIdent = task.cacheIdent || serialize(task.cacheKeys);
33+
cacheData.cacheIdent =
34+
cacheData.cacheIdent || serialize(cacheData.cacheKeys);
3435

3536
let cachedResult;
3637

3738
try {
38-
cachedResult = await cacache.get(this.cache, task.cacheIdent);
39+
cachedResult = await cacache.get(this.cache, cacheData.cacheIdent);
3940
} catch (ignoreError) {
4041
// eslint-disable-next-line no-undefined
4142
return undefined;
@@ -46,17 +47,17 @@ export default class Webpack4Cache {
4647
);
4748
}
4849

49-
async store(task) {
50-
if (!this.weakCache.has(task.assetSource)) {
51-
this.weakCache.set(task.assetSource, task.output);
50+
async store(cacheData) {
51+
if (!this.weakCache.has(cacheData.source)) {
52+
this.weakCache.set(cacheData.source, cacheData.output);
5253
}
5354

5455
if (!this.cache) {
5556
// eslint-disable-next-line no-undefined
5657
return undefined;
5758
}
5859

59-
const { cacheIdent, output } = task;
60+
const { cacheIdent, output } = cacheData;
6061

6162
return cacache.put(this.cache, cacheIdent, JSON.stringify(output.source()));
6263
}

src/Webpack5Cache.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,19 @@ export default class Cache {
33
this.cache = compilation.getCache('CompressionWebpackPlugin');
44
}
55

6-
async get(task) {
6+
async get(cacheData) {
77
// eslint-disable-next-line no-param-reassign
8-
task.eTag = task.eTag || this.cache.getLazyHashedEtag(task.assetSource);
8+
cacheData.eTag =
9+
cacheData.eTag || this.cache.getLazyHashedEtag(cacheData.source);
910

10-
return this.cache.getPromise(task.assetName, task.eTag);
11+
return this.cache.getPromise(cacheData.assetName, cacheData.eTag);
1112
}
1213

13-
async store(task) {
14-
return this.cache.storePromise(task.assetName, task.eTag, task.output);
14+
async store(cacheData) {
15+
return this.cache.storePromise(
16+
cacheData.assetName,
17+
cacheData.eTag,
18+
cacheData.output
19+
);
1520
}
1621
}

src/index.js

Lines changed: 90 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ class CompressionPlugin {
137137
delete compilation.assets[name];
138138
}
139139

140-
compress(input) {
140+
runCompressionAlgorithm(input) {
141141
return new Promise((resolve, reject) => {
142142
const { algorithm, compressionOptions } = this;
143143

@@ -156,128 +156,121 @@ class CompressionPlugin {
156156
});
157157
}
158158

159-
*getTask(compilation, assetName) {
160-
const { source: assetSource, info: assetInfo } = CompressionPlugin.getAsset(
161-
compilation,
162-
assetName
159+
async compress(compilation, assets, CacheEngine, weakCache) {
160+
const assetNames = Object.keys(
161+
typeof assets === 'undefined' ? compilation.assets : assets
162+
).filter((assetName) =>
163+
// eslint-disable-next-line no-undefined
164+
ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(assetName)
163165
);
164166

165-
if (assetInfo.compressed) {
166-
yield false;
167-
}
168-
169-
let relatedName;
170-
171-
if (typeof this.options.algorithm === 'function') {
172-
let filenameForRelatedName = this.options.filename;
173-
174-
const index = filenameForRelatedName.lastIndexOf('?');
175-
176-
if (index >= 0) {
177-
filenameForRelatedName = filenameForRelatedName.substr(0, index);
178-
}
179-
180-
relatedName = `${path.extname(filenameForRelatedName).slice(1)}ed`;
181-
} else {
182-
relatedName = `${this.options.algorithm}ed`;
183-
}
184-
185-
if (assetInfo.related && assetInfo.related[relatedName]) {
186-
yield false;
167+
if (assetNames.length === 0) {
168+
return Promise.resolve();
187169
}
188170

189-
let input = assetSource.source();
190-
191-
if (!Buffer.isBuffer(input)) {
192-
input = Buffer.from(input);
193-
}
171+
const scheduledTasks = [];
172+
const cache = new CacheEngine(
173+
compilation,
174+
{ cache: this.options.cache },
175+
weakCache
176+
);
194177

195-
if (input.length < this.options.threshold) {
196-
yield false;
197-
}
178+
for (const assetName of assetNames) {
179+
scheduledTasks.push(
180+
(async () => {
181+
const { source, info } = CompressionPlugin.getAsset(
182+
compilation,
183+
assetName
184+
);
198185

199-
const task = { assetName, assetSource, assetInfo, input, relatedName };
186+
if (info.compressed) {
187+
return;
188+
}
200189

201-
if (CompressionPlugin.isWebpack4()) {
202-
task.cacheKeys = {
203-
nodeVersion: process.version,
204-
// eslint-disable-next-line global-require
205-
'compression-webpack-plugin': require('../package.json').version,
206-
algorithm: this.algorithm,
207-
originalAlgorithm: this.options.algorithm,
208-
compressionOptions: this.compressionOptions,
209-
assetName,
210-
contentHash: crypto.createHash('md4').update(input).digest('hex'),
211-
};
212-
}
190+
let relatedName;
213191

214-
yield task;
215-
}
192+
if (typeof this.options.algorithm === 'function') {
193+
let filenameForRelatedName = this.options.filename;
216194

217-
afterTask(compilation, task) {
218-
const { output, input } = task;
195+
const index = filenameForRelatedName.lastIndexOf('?');
219196

220-
if (output.source().length / input.length > this.options.minRatio) {
221-
return;
222-
}
197+
if (index >= 0) {
198+
filenameForRelatedName = filenameForRelatedName.substr(0, index);
199+
}
223200

224-
const { assetSource, assetName } = task;
225-
const newAssetName = CompressionPlugin.interpolateName(
226-
assetName,
227-
this.options.filename
228-
);
201+
relatedName = `${path.extname(filenameForRelatedName).slice(1)}ed`;
202+
} else {
203+
relatedName = `${this.options.algorithm}ed`;
204+
}
229205

230-
CompressionPlugin.emitAsset(compilation, newAssetName, output, {
231-
compressed: true,
232-
});
206+
if (info.related && info.related[relatedName]) {
207+
return;
208+
}
233209

234-
if (this.options.deleteOriginalAssets) {
235-
// eslint-disable-next-line no-param-reassign
236-
CompressionPlugin.deleteAsset(compilation, assetName);
237-
} else {
238-
CompressionPlugin.updateAsset(compilation, assetName, assetSource, {
239-
related: { [task.relatedName]: newAssetName },
240-
});
241-
}
242-
}
210+
let input = source.source();
243211

244-
async runTasks(compilation, assetNames, CacheEngine, weakCache) {
245-
const scheduledTasks = [];
246-
const cache = new CacheEngine(
247-
compilation,
248-
{
249-
cache: this.options.cache,
250-
},
251-
weakCache
252-
);
212+
if (!Buffer.isBuffer(input)) {
213+
input = Buffer.from(input);
214+
}
253215

254-
for (const assetName of assetNames) {
255-
scheduledTasks.push(
256-
(async () => {
257-
const task = this.getTask(compilation, assetName).next().value;
216+
if (input.length < this.options.threshold) {
217+
return;
218+
}
258219

259-
if (!task) {
260-
return Promise.resolve();
220+
const cacheData = { source };
221+
222+
if (CompressionPlugin.isWebpack4()) {
223+
cacheData.cacheKeys = {
224+
nodeVersion: process.version,
225+
// eslint-disable-next-line global-require
226+
'compression-webpack-plugin': require('../package.json').version,
227+
algorithm: this.algorithm,
228+
originalAlgorithm: this.options.algorithm,
229+
compressionOptions: this.compressionOptions,
230+
assetName,
231+
contentHash: crypto.createHash('md4').update(input).digest('hex'),
232+
};
233+
} else {
234+
cacheData.assetName = assetName;
261235
}
262236

263-
task.output = await cache.get(task, { RawSource });
237+
let output = await cache.get(cacheData, { RawSource });
264238

265-
if (!task.output) {
239+
if (!output) {
266240
try {
267-
// eslint-disable-next-line no-param-reassign
268-
task.output = new RawSource(await this.compress(task.input));
241+
output = new RawSource(await this.runCompressionAlgorithm(input));
269242
} catch (error) {
270243
compilation.errors.push(error);
271244

272-
return Promise.resolve();
245+
return;
273246
}
274247

275-
await cache.store(task);
248+
cacheData.output = output;
249+
250+
await cache.store(cacheData);
276251
}
277252

278-
this.afterTask(compilation, task);
253+
if (output.source().length / input.length > this.options.minRatio) {
254+
return;
255+
}
279256

280-
return Promise.resolve();
257+
const newAssetName = CompressionPlugin.interpolateName(
258+
assetName,
259+
this.options.filename
260+
);
261+
262+
CompressionPlugin.emitAsset(compilation, newAssetName, output, {
263+
compressed: true,
264+
});
265+
266+
if (this.options.deleteOriginalAssets) {
267+
// eslint-disable-next-line no-param-reassign
268+
CompressionPlugin.deleteAsset(compilation, assetName);
269+
} else {
270+
CompressionPlugin.updateAsset(compilation, assetName, source, {
271+
related: { [relatedName]: newAssetName },
272+
});
273+
}
281274
})()
282275
);
283276
}
@@ -291,29 +284,6 @@ class CompressionPlugin {
291284

292285
apply(compiler) {
293286
const pluginName = this.constructor.name;
294-
const matchObject = ModuleFilenameHelpers.matchObject.bind(
295-
// eslint-disable-next-line no-undefined
296-
undefined,
297-
this.options
298-
);
299-
const compressionFn = async (
300-
compilation,
301-
assets,
302-
CacheEngine,
303-
weakCache
304-
) => {
305-
const assetNames = Object.keys(
306-
typeof assets === 'undefined' ? compilation.assets : assets
307-
).filter((assetName) => matchObject(assetName));
308-
309-
if (assetNames.length === 0) {
310-
return Promise.resolve();
311-
}
312-
313-
await this.runTasks(compilation, assetNames, CacheEngine, weakCache);
314-
315-
return Promise.resolve();
316-
};
317287

318288
if (CompressionPlugin.isWebpack4()) {
319289
// eslint-disable-next-line global-require
@@ -322,7 +292,7 @@ class CompressionPlugin {
322292

323293
compiler.hooks.emit.tapPromise({ name: pluginName }, (compilation) =>
324294
// eslint-disable-next-line no-undefined
325-
compressionFn(compilation, undefined, CacheEngine, weakCache)
295+
this.compress(compilation, undefined, CacheEngine, weakCache)
326296
);
327297
} else {
328298
// eslint-disable-next-line global-require
@@ -337,7 +307,7 @@ class CompressionPlugin {
337307
name: pluginName,
338308
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER,
339309
},
340-
(assets) => compressionFn(compilation, assets, CacheEngine)
310+
(assets) => this.compress(compilation, assets, CacheEngine)
341311
);
342312

343313
compilation.hooks.statsPrinter.tap(pluginName, (stats) => {

test/cache-option.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ if (getCompiler.isWebpack4()) {
3636
]);
3737
});
3838

39-
afterEach(() => {
39+
afterAll(() => {
4040
return Promise.all([
4141
cacache.rm.all(falseCacheDirectory),
4242
cacache.rm.all(cacheDir),

0 commit comments

Comments
 (0)