How to Minify HTML, CSS and JavaScript Files With "html-minifier"
In this question, we explain how to minify and clean HTML, CSS and JavaScript files. Before that, first, make sure that you have NodeJS installed in your system. If not, read the “NodeJS NPM package manager installation” section of the
How To Setup A Linux, Apache, MySQL, PHP Dev Environment On Ubuntu guide. After that, install the html-minifier
package by running the following command.
npm install html-minifier -g
Then, run the html-minifier
command to minify and clean all the HTML, CSS and JS files in the current directory.
html-minifier --input-dir . --output-dir . --remove-comments --collapse-whitespace --minify-css --minify-js
But sometimes it can be failed to minify and clean all the files due to invalid codes and markup errors. For that kind of situation, try to fix the related file if possible or otherwise run the command targeting a specific file type.
For example, you can minify only the HTML files by running the above command with the --file-ext
flag.
html-minifier --input-dir . --output-dir . --remove-comments --collapse-whitespace --minify-css --minify-js --file-ext html
Likewise, you can run the same command for other file types such as css
and js
by adding them one by one to the --file-ext
.