Is there any module in NodeJS to concatenate and minify JavaScript files?
Maybe not exactly what you're looking for but Enderjs could work.
If you already have uglify-js
, your code uses some of the latest ES6 features (ECMAScript 2015) and it just gave you back parse errors on the first run, then install uglify-es:
npm install uglify-es -g
Or:
npm install mishoo/UglifyJS2#harmony
The explanation is in uglify-js-es6 package:
This is a temporary package containing the latest release of the 'harmony' branch of uglifyjs (UglifyJS2).
You can still run it normally with the uglifyjs
command. A compress and mangle example:
uglifyjs -c -m -o js/es6stuff.js -- js/es6stuff/*.js
Which will produce a single file with all the JS files of a folder. The double dash (--
) just prevents input files being used as option arguments.
If you're using Connect, then I've had good luck with Connect-Assetmanager
Try these two plugins for Grunt
https://www.npmjs.org/package/grunt-contrib-concat
https://www.npmjs.org/package/grunt-contrib-uglify
You can install everything you need like so:
npm install grunt
npm install grunt-cli
npm install grunt-contrib-concat
npm install grunt-contrib-uglify
Then create your grunt file, like so:
Gruntfile.js
module.exports = function(grunt){
grunt.initConfig({
concat: {
options: {
process: function(src, path){
return '\n/* Source: ' + path + ' */\n' + src;
}
},
src: [
'../src/**/*.js'
],
dest: '../bin/app-debug.js'
},
uglify: {
src: '../bin/app-debug.js',
dest: '../bin/app.js'
},
watch: {
options: {
atBegin: true,
event: ['all']
},
src: {
files: '../src/**/*.js',
tasks: ['concat']
},
dist: {
files: '../bin/app-debug.js',
tasks: ['uglify']
},
}
}
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['watch']);
}
Finally, type grunt
in the terminal and Grunt will start watching your JavaScript files for changes and automatically concat and uglify them (whenever you save a change to your js files in ../src/
I'd definitely suggest the Closure Compiler's simple mode.
UglifyJS is a Node module that is all about minifying javascript. I don't think it also joins files, but there might be an option I missed.
Edit: With UglifyJS 2, it has built in concatenation as well.
If you want to do this inline in your node app it's really easy. This allows you to dynamically generate your minified/concatenated js script at runtime without using the grunt or yeoman way.
npm install uglify-js
and in your module:
var fs = require('fs');
var uglify = require("uglify-js");
var uglified = uglify.minify(['file1.js', 'file2.js', 'file3.js']);
fs.writeFile('concat.min.js', uglified.code, function (err){
if(err) {
console.log(err);
} else {
console.log("Script generated and saved:", 'concat.min.js');
}
});