How to minify multiple Javascript files in a folder with UglifyJS? How to minify multiple Javascript files in a folder with UglifyJS? node.js node.js

How to minify multiple Javascript files in a folder with UglifyJS?


I know it might seem like a huge step but I would really recommend using grunt.It's really simple once you get the hang of it.

Here's a crash course:

  1. Install NodeJS
  2. Install Grunt CLI (just enter this in console/terminal):

    npm install -g grunt-cli
  3. Create a simple package.json file in the root of your project:

    {  "name": "my-project-name",  "version": "1.0.0",  "devDependencies": {    "grunt": "~0.4.2",    "grunt-contrib-uglify": "~0.2.4",    "grunt-contrib-watch" : "~0.5.3"  }}
  4. Once you have that, just type: npm install to the console (in the root of your project).This will install the necessary grunt plugins/dependencies (from the package file above).

  5. Now create a simple gruntfile.js in the root of your project (it's a kind of config for your project):

    module.exports = function (grunt) {    grunt.initConfig({
        // define source files and their destinations    uglify: {        files: {             src: 'js/*.js',  // source files mask            dest: 'jsm/',    // destination folder            expand: true,    // allow dynamic building            flatten: true,   // remove all unnecessary nesting            ext: '.min.js'   // replace .js to .min.js        }    },    watch: {        js:  { files: 'js/*.js', tasks: [ 'uglify' ] },    }});// load pluginsgrunt.loadNpmTasks('grunt-contrib-watch');grunt.loadNpmTasks('grunt-contrib-uglify');// register at least this one taskgrunt.registerTask('default', [ 'uglify' ]);
    };
  6. Once that's done you just need to build it. Type in the console:

    grunt

    or - better - if you type execute the command below - grunt will monitor your source files for changes, and if you change any of them - it will build them automatically:

    grunt watch --force

You can then add more plugins, like: css minification, css preprocessors (less, sass, stylus), jshint, etc.


If you're on Linux/Mac and have access to bash, you can use uglifyjs on multiple JS files like so:

rm *.min.js; for f in *.js; do short=${f%.js}; uglifyjs $f > $short.min.js; done


npm-only way:

  1. run:

    npm install uglifyjs-folder --save-dev
  2. and afterwards add to your package.json something like:

    "uglifyjs": "uglifyjs-folder js -eo jsm"
  3. then run:

     npm run uglifyjs

Please note, if you'd need to generate to the same folder as the source files are (js), following should do the job:

  1. run:

    npm install del-cli uglifyjs-folder --save-dev
  2. and afterwards add to your package.json something like:

    "uglifyjs": "del js/*.min.js; uglifyjs-folder js -eo js"
  3. then run:

     npm run uglifyjs