Skip to content

Instantly share code, notes, and snippets.

@nitind
Last active November 17, 2016 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitind/a3d7932ed118fb2cf7b7208df8e6f1c8 to your computer and use it in GitHub Desktop.
Save nitind/a3d7932ed118fb2cf7b7208df8e6f1c8 to your computer and use it in GitHub Desktop.
A transform function to use with copy-webpack-plugin that attempts to gzip assets as they're copied.
// A transform function to use with copy-webpack-plugin that
// gzips assets as they're copied.
//
var gziptee = function(src, dest) {
const gzipSmallerThan = 0.8;
function mkdirhier(dir) {
if(path.resolve('.').length < dir.length) {
mkdirhier(path.dirname(dir));
}
if (!fs.existsSync(dir)) {
fs.appendFileSync('gzipper.log', 'Making ' +dir+ '\n');
fs.mkdirSync(dir, 0777 & (~process.umask()));
}
}
var gzipper = function(content, _path) {
gzip(content, function(err, result) {
if (err) {
console.error(err);
}
else {
if((result.length / content.length) < gzipSmallerThan) {
var gzpath = path.resolve('.', path.join(dest, path.relative(src, _path)) + '.gz');
fs.appendFileSync('gzipper.log', _path + ' to ' + gzpath + '\n');
// The file hasn't been copied yet, so its parent might not exist yet
mkdirhier(path.dirname(gzpath));
fs.writeFile(gzpath, result);
}
}
});
return content;
}
return gzipper;
}
new CopyWebpackPlugin([
{
from: 'src/assets',
to: 'assets',
transform: gziptee('src/assets', 'dist/assets')
}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment