Last active
August 29, 2015 14:16
-
-
Save primaryobjects/7cfef5806d156e1a393a to your computer and use it in GitHub Desktop.
3 Tools for Minifying Your Web Project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
html-minifier | |
https://www.npmjs.com/package/html-minifier | |
UglifyCSS | |
https://github.com/fmarcia/UglifyCSS | |
UglifyJS2 | |
https://github.com/mishoo/UglifyJS2 | |
Usage: | |
*/ | |
var UglifyJS = require('uglify-js'); | |
var UglifyCSS = require('uglifycss'); | |
var htmlminify = require('html-minifier').minify; | |
var baseFolder = 'myprojectname'; | |
// Minify scripts. | |
minifyJs('../scripts/script.js'); | |
// Minify css. | |
minifyCss('../css/style.css'); | |
// Minify html. | |
minifyHtml('../index.html'); | |
function minifyJs(filePath) { | |
var result = UglifyJS.minify(filePath); | |
var fileName = './' + baseFolder + '/scripts/' + path.basename(filePath); | |
// Save minified file. | |
saveFile(fileName, result.code); | |
} | |
function minifyCss(filePath) { | |
var result = UglifyCSS.processFiles([ filePath ]); | |
var fileName = './' + baseFolder + '/css/' + path.basename(filePath); | |
// Save minified file. | |
saveFile(fileName, result); | |
} | |
function minifyHtml(filePath) { | |
var text = fs.readFileSync(filePath, encoding='utf8'); | |
var result = htmlminify(text, { | |
removeComments: true, | |
collapseWhitespace: true | |
}); | |
var fileName = './' + baseFolder + '/' + path.basename(filePath); | |
// Save minified file. | |
saveFile(fileName, result); | |
} | |
function saveFile(filePath, content) { | |
fs.writeFile(filePath, content, function(err) { | |
if(err) { | |
console.log(err); | |
} else { | |
console.log("Minified " + filePath); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment