forked from webpack-contrib/compression-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
64 lines (61 loc) · 2.38 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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var async = require("async");
var RawSource = require("webpack/lib/RawSource");
function CompressionPlugin(options) {
options = options || {};
this.asset = options.asset || "{file}.gz";
this.algorithm = options.algorithm || "gzip";
if(typeof this.algorithm === "string") {
if (this.algorithm === "zopfli") {
try {
var zopfli = require("node-zopfli");
} catch(err) {
throw new Error("node-zopfli not found");
}
this.algorithm = function (content, fn) {
zopfli.gzip(content, {
verbose: options.hasOwnProperty('verbose') ? options.verbose : false,
verbose_more: options.hasOwnProperty('verbose_more') ? options.verbose_more : false,
numiterations: options.numiterations ? options.numiterations : 15,
blocksplitting: options.hasOwnProperty('blocksplitting') ? options.blocksplitting : true,
blocksplittinglast: options.hasOwnProperty('blocksplittinglast') ? options.blocksplittinglast : false,
blocksplittingmax: options.blocksplittingmax ? options.blocksplittingmax : 15
}, fn);
};
} else {
var zlib = require("zlib");
this.algorithm = zlib[this.algorithm];
if(!this.algorithm) throw new Error("Algorithm not found in zlib");
this.algorithm = this.algorithm.bind(zlib);
}
}
this.regExp = options.regExp;
this.threshold = options.threshold || 0;
this.minRatio = options.minRatio || 0.8;
}
module.exports = CompressionPlugin;
CompressionPlugin.prototype.apply = function(compiler) {
compiler.plugin("this-compilation", function(compilation) {
compilation.plugin("optimize-assets", function(assets, callback) {
async.forEach(Object.keys(assets), function(file, callback) {
if(this.regExp && !this.regExp.test(file)) return callback();
var asset = assets[file];
var content = asset.source();
if(!Buffer.isBuffer(content))
content = new Buffer(content, "utf-8");
var originalSize = content.length;
if(originalSize < this.threshold) return callback();
this.algorithm(content, function(err, result) {
if(err) return callback(err);
if(result.length / originalSize > this.minRatio) return callback();
var newFile = this.asset.replace(/\{file\}/g, file);
assets[newFile] = new RawSource(result);
callback();
}.bind(this));
}.bind(this), callback);
}.bind(this));
}.bind(this));
};