Skip to content

Instantly share code, notes, and snippets.

@2no
Last active December 15, 2015 03:38
Show Gist options
  • Save 2no/5195356 to your computer and use it in GitHub Desktop.
Save 2no/5195356 to your computer and use it in GitHub Desktop.
インデントや複数行続く改行を削除(script, style 要素は除外)
module.exports = function(grunt)
{
'use strict';
grunt.config.init({
html_clean: {
html: {
src: 'sample.html',
newline: '\r\n', // 省略可
},
},
});
grunt.task.registerMultiTask('html_clean',
'delete empty lines and indent',
function() {
var self = this,
config = grunt.config.get(this.name),
files = grunt.file.expand(this.data.src);
files.forEach(function(file) {
var dest, matches, nl, mSrc, mDest,
conf = config[self.target] || {},
nl = conf.newline,
src = grunt.file.read(file),
pattern = /<(script|style)\b[\s\S]*?>([\s\S]*?)<\/\1\b[\s\S]*?>/igm;
matches = src.match(/\r\n|\n|\r/);
if (!nl) {
nl = matches ? matches[0] : '\n';
}
mSrc = src.match(pattern);
dest = src.replace(/\r\n|\n|\r/gm, '\n');
dest = dest.replace(/^([\s\t\r\n\0\0xB]*|\n*$)/gm, '');
dest = dest.replace(/^\n{2,}/gm, '\n');
dest = dest.replace(/\n/gm, nl);
if (mSrc) {
mDest = dest.match(pattern);
mSrc.forEach(function(match, index) {
dest = dest.replace(mDest[index], match);
});
}
grunt.file.write(file, dest);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment