Skip to content

Commit 3bb0ddb

Browse files
authored
webpack: detect if node-zopfli is installed before attemping to use it (#4712)
zopfli is not required by any means, especially for local development and CI. So if there's an issue installing this, we should just avoid attempting to compress rather than error all over the place. This keeps the error to just a simple warning instead so we're aware and can see this if something were to fail in a production build, but won't affect any other environment. Also, note that this is explicitly checking against paths rather than testing with a `require()` since with npm@2, the dependency is actually a sub-dependnecy of `compression-webpack-plugin` and can't be `require`d from outside that module. So it doesn't help to test that. And with npm@3, the module gets flatted to the top level, so we need to check both places.
1 parent 45c42b7 commit 3bb0ddb

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

webpack.config.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,16 +185,30 @@ var config = {
185185
'#cheap-module-eval-source-map'
186186
};
187187

188+
189+
function hasZopfli() {
190+
return (
191+
// npm@2
192+
fs.existsSync('node_modules/compression-webpack-plugin/node_modules/node-zopfli') ||
193+
// npm@3
194+
fs.existsSync('node_modules/node-zopfli')
195+
);
196+
}
197+
188198
// This compression-webpack-plugin generates pre-compressed files
189199
// ending in .gz, to be picked up and served by our internal static media
190200
// server as well as nginx when paired with the gzip_static module.
191201
if (IS_PRODUCTION) {
202+
var algorithm = hasZopfli() ? 'zopfli' : 'gzip';
192203
config.plugins.push(new (require('compression-webpack-plugin'))({
193204
// zopfli gives us a better gzip compression
194205
// See: http://googledevelopers.blogspot.com/2013/02/compress-data-more-densely-with-zopfli.html
195-
algorithm: 'zopfli',
206+
algorithm: algorithm,
196207
regExp: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
197208
}));
209+
if (algorithm === 'gzip') {
210+
console.warn('!! missing node-zopfli, so falling back to gzip.');
211+
}
198212
}
199213

200214
module.exports = config;

0 commit comments

Comments
 (0)