Skip to content

Commit

Permalink
Merge pull request #6 from haensl/feature/5
Browse files Browse the repository at this point in the history
Replace cheerio with minify-inline-json.
  • Loading branch information
haensl authored Mar 15, 2018
2 parents 99d479b + 1b2dea5 commit 9357255
Show file tree
Hide file tree
Showing 5 changed files with 1,792 additions and 29 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 1.3.0
* [#5: Use minify-inline-json instead of cheerio.](https://github.com/haensl/gulp-minify-inline-json/issues/5)

# 1.2.0
* Add option to specify mime types

Expand Down
38 changes: 12 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const through = require('through2');
const cheerio = require('cheerio');
const gutil = require('gulp-util');
const minifyInlineJson = require('minify-inline-json');

const PLUGIN_NAME = require('./package').name;
const DEFAULTS = {
Expand All @@ -10,7 +10,7 @@ const DEFAULTS = {
]
};

module.exports = (options = {}) =>
module.exports = (opts = {}) =>
through.obj((file, encoding, callback) => {
if (file.isNull()) {
return callback(null, file);
Expand All @@ -20,31 +20,17 @@ module.exports = (options = {}) =>
return callback(new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported.'));
}

const $ = cheerio.load(file.contents.toString());
let didMinify = false;

const mimeTypes = Array.isArray(options.mimeTypes)
? options.mimeTypes
: DEFAULTS.mimeTypes;

$(mimeTypes.map((type) => `script[type="${type}"]`).join(','))
.each(function() {
const script = $(this);
const scriptText = script.contents().text().trim();

if (scriptText.length) {
try {
script.text(JSON.stringify(JSON.parse(scriptText)));
didMinify = true;
} catch (e) {
return callback(new gutil.PluginError(PLUGIN_NAME, e));
}
}
});

if (didMinify) {
file.contents = new Buffer($.html());
if (typeof opts.mimeTypes === 'string') {
opts.mimeTypes = [ opts.mimeTypes];
}

const options = Object.assign({}, DEFAULTS, opts);

if (!Array.isArray(options.mimeTypes)) {
return callback(new gutil.PluginError(PLUGIN_NAME, 'Invalid option: mimeTypes must be string or Array of strings'));
}

file.contents = new Buffer(minifyInlineJson(file.contents.toString(), options));

callback(null, file);
});
Loading

0 comments on commit 9357255

Please sign in to comment.