1+ /*
2+ MIT License http://www.opensource.org/licenses/mit-license.php
3+ Author Tobias Koppers @sokra
4+ */
5+ var async = require ( "async" ) ;
6+
7+ var Source = require ( "webpack/lib/Source" ) ;
8+
9+ function RawSource ( value ) {
10+ Source . call ( this ) ;
11+ this . _value = value ;
12+ }
13+ module . exports = RawSource ;
14+
15+ RawSource . prototype = Object . create ( Source . prototype ) ;
16+ RawSource . prototype . _bake = function ( ) {
17+ return {
18+ source : this . _value
19+ } ;
20+ } ;
21+
22+ function CompressionPlugin ( options ) {
23+ options = options || { } ;
24+ this . asset = options . asset || "{file}.gz" ;
25+ this . algorithm = options . algorithm || "gzip" ;
26+ if ( typeof this . algorithm === "string" ) {
27+ var zlib = require ( "zlib" ) ;
28+ this . algorithm = zlib [ this . algorithm ] ;
29+ if ( ! this . algorithm ) throw new Error ( "Algorithm not found in zlib" ) ;
30+ this . algorithm = this . algorithm . bind ( zlib ) ;
31+ }
32+ this . regExp = options . regExp ;
33+ this . threshold = options . threshold || 0 ;
34+ this . minRatio = options . minRatio || 0.8 ;
35+ }
36+ module . exports = CompressionPlugin ;
37+
38+ CompressionPlugin . prototype . apply = function ( compiler ) {
39+ compiler . plugin ( "compilation" , function ( compilation ) {
40+ compilation . plugin ( "optimize-assets" , function ( assets , callback ) {
41+ async . forEach ( Object . keys ( assets ) , function ( file , callback ) {
42+ if ( this . regExp && ! this . regExp . test ( file ) ) return callback ( ) ;
43+ var asset = assets [ file ] ;
44+ var content = asset . source ( ) ;
45+ if ( ! Buffer . isBuffer ( content ) )
46+ content = new Buffer ( content , "utf-8" ) ;
47+ var originalSize = content . length ;
48+ if ( originalSize < this . threshold ) return callback ( ) ;
49+ this . algorithm ( content , function ( err , result ) {
50+ if ( err ) return callback ( err ) ;
51+ if ( result . length / originalSize > this . minRatio ) return callback ( ) ;
52+ var newFile = this . asset . replace ( / \{ f i l e \} / g, file ) ;
53+ assets [ newFile ] = new RawSource ( result ) ;
54+ callback ( ) ;
55+ } . bind ( this ) ) ;
56+ } . bind ( this ) , callback ) ;
57+ } . bind ( this ) ) ;
58+ } . bind ( this ) ) ;
59+ } ;
0 commit comments