Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify HTML using a Node.js module

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...

like image 974
Maxim Yefremov Avatar asked Sep 26 '13 03:09

Maxim Yefremov


People also ask

How do I minify node js in HTML?

-- 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. Note that the library parses the input as HTML, not XHTML.

How do you minify an HTML file?

Go to minifycode.com and click the CSS minifier tab. Then paste the CSS code into the input box and click the Minify CSS button. After the new minified code is generated, copy the code. Then go back to the css file of your website and replace the code with the new minified version.

Should you minify node modules?

For a NodeJS audience your package does not have to be minified, since node runtimes normally have direct file access to the node_modules folder. No network transfers are required, and no additional code transformations are performed prior to running the code.


1 Answers

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.

like image 62
hexacyanide Avatar answered Oct 21 '22 21:10

hexacyanide