最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Minify HTML using a Node.js module - Stack Overflow

programmeradmin3浏览0评论

I have HTML in a variable and before render it and I want to minify it. I know there are console minifiers such as:

  • html-minifier

But I want to minify in code, like this:

var minifier = require ('some-minifier');
var notMinifiedHtml = "<html>...</html>";
var minifiedHtml = minifier(notMinifiedHtml);

But I don't know such some-minifier library...

I have HTML in a variable and before render it and I want to minify it. I know there are console minifiers such as:

  • html-minifier

But I want to minify in code, like this:

var minifier = require ('some-minifier');
var notMinifiedHtml = "<html>...</html>";
var minifiedHtml = minifier(notMinifiedHtml);

But I don't know such some-minifier library...

Share Improve this question edited Oct 1, 2013 at 4:07 hexacyanide 91.7k31 gold badges165 silver badges162 bronze badges asked Sep 26, 2013 at 3:40 Maxim YefremovMaxim Yefremov 14.2k28 gold badges123 silver badges170 bronze badges 10
  • Why? If you're concerned about transmitting data over the wire, use compression and forget about minification. – Matt Ball Commented Sep 26, 2013 at 3:42
  • 1 @MattBall because minified html loads faster on ther browser – Maxim Yefremov Commented Sep 26, 2013 at 3:44
  • What types of minification are you after? Whitespace removal would be somewhat easy with regex, but do you want to go further with, say, variable replacement and such? – Ehryk Commented Sep 26, 2013 at 3:45
  • 3 @Ehryk You should never process HTML with regex. – Alex W Commented Sep 26, 2013 at 3:47
  • 1 @MattBall even if it did take more time to load, that wasn't the question asked, nor was it about all the ways to reduce page load times, nor was it 'suggest doing something else entirely.' – Ehryk Commented Sep 26, 2013 at 4:47
 |  Show 5 more comments

1 Answer 1

Reset to default 20

The module you specified, html-minifier, already does what you're asking for. This is how it's used:

var minify = require('html-minifier').minify;
var input = '<!-- foo --><div>baz</div><!-- bar\n\n moo -->';
var output = minify(input, options);

The options object requires at least one of the boolean flags shown below. If no flags are specified, the minifier will just return the string that was passed in as input.

removeComments
removeCommentsFromCDATA
collapseWhitespace
collapseBooleanAttributes
removeAttributeQuotes
removeRedundantAttributes
useShortDoctype
removeEmptyAttributes
removeOptionalTags
removeEmptyElements

Note that the library parses the input as HTML, not XHTML.

发布评论

评论列表(0)

  1. 暂无评论