Skip to content

Instantly share code, notes, and snippets.

@urakey
Forked from 2no/Gruntfile.js
Last active December 15, 2015 03:38
Show Gist options
  • Save urakey/5195386 to your computer and use it in GitHub Desktop.
Save urakey/5195386 to your computer and use it in GitHub Desktop.
Snippet: html_clean.coffee
module.exports = (grunt) ->
'use strict'
options =
html_clean:
html:
src: 'sample.html'
newline: '\r\n'
grunt.initConfig(options)
grunt.loadTasks 'tasks'
# ************************************
# Regist Tasks - html_clean
# ************************************
module.exports = (grunt) ->
'use strict'
grunt.task.registerMultiTask 'html_clean', 'delete empty lines and indent', ->
self = this
config = grunt.config.get(@name)
files = grunt.file.expand(@data.src)
files.forEach (file) ->
conf = config[self.target] or {}
nl = conf.newline
src = grunt.file.read(file)
pattern = /<(script|style)\b[\s\S]*?>([\s\S]*?)<\/\1\b[\s\S]*?>/gm
matches = src.match(/\r\n|\n|\r/)
nl = (if matches then matches[0] else "\n") unless nl
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 (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