makestatic-emit-gzip
Version:
Emits static gzip files
73 lines (61 loc) • 1.88 kB
JavaScript
const when = require('when')
const zlib = require('zlib')
/**
* Creates static `.gz` files for each output file.
*
* This plugin is enabled by the `core-standard` configuration when the
* `gzip` option is given.
*
* @class EmitGzip
*
* @see /docs/api/cli/ Command Line Interface
* @see /docs/api/core-standard/ Core Standard
*/
class EmitGzip {
/**
* For each file compress the file `content` using the `zlib` module and
* add a new file to the pipeline with a `.gz` file extension.
*
* Before this plugin is executed files must have been assigned a `content`
* buffer.
*
* Files marked as `transient` are ignored.
*
* If the `gzip` context option is not set this function call is a noop.
*
* @function sources
* @member EmitGzip
*
* @param {Object} file the file being processed.
* @param {Object} context the processing context.
* @param {Object} conf the plugin configuration.
*/
sources (file, context, conf = {}) {
const log = context.log
const opts = context.options
if (file.transient || opts.gzip === false) {
return
}
return when.promise((resolve, reject) => {
zlib.gzip(file.content, conf, (err, content) => {
/* istanbul ignore next: not going to mock zlib error */
if (err) {
return reject(err)
}
const ext = '.gz'
let key = file.output + ext
/* istanbul ignore next: not going to mock webpack integration here */
if (opts.pack) {
key = file.relative(
context.options.output, true, file.output) + ext
}
const gzip = context.getFile(
{output: key, content: content, name: file.name + ext})
log.info('[gzip] %s', gzip.output)
context.list.add(gzip)
resolve()
})
})
}
}
module.exports = EmitGzip