Skip to content

Instantly share code, notes, and snippets.

@clintconklin
Last active February 6, 2017 15:12
Show Gist options
  • Save clintconklin/7393526 to your computer and use it in GitHub Desktop.
Save clintconklin/7393526 to your computer and use it in GitHub Desktop.
Optimizing multiple files with grunt via grunt-contrib-requirejs: http://blog.clintconklin.com/optimizing-multiple-javascript-files-with-grunt-and-requirejs/
module.exports = function(grunt) {
var matches = grunt.file.expand('scripts/template-scripts/**/index.js');
var requirejsOptions = {};
if (matches.length > 0) {
for (var x = 0; x < matches.length; x++) {
var path = matches[x].replace(/\/index\.js/, '');
requirejsOptions['task' + x] = {
"options": {
"baseUrl": "./",
"wrap": true,
"name": path + "/index",
"out": path + "/index.min.js",
"optimize": "uglify2",
"uglify2": {
"mangle": false
},
"generateSourceMaps": true,
"preserveLicenseComments": false,
"done": function(done, output) {
done();
}
}
};
}
}
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: requirejsOptions
});
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['requirejs']);
};
@shybovycha
Copy link

shybovycha commented Feb 6, 2017

I'd use the reduce instead of for loop and drop the unnecessary if statement:

module.exports = function (grunt) {
    var matches = grunt.file.expand('scripts/template-scripts/**/index.js');

    var requireJsOptions = matches.reduce(function (acc, match, index) {
        var path = match.replace(/\/index\.js$/, '');

        acc['task' + index] = {
            options: {
                baseUrl: './',
                wrap: true,
                name: path + '/index',
                out: path + '/index.min.js',
                optimize: 'uglify2',
                uglify2: {
                    mangle: false
                },
                generateSourceMaps: true,
                preserveLicenseComments: false,
                done: function (done, output) {
                    done();
                }
            }
        };
    }, {});

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        requirejs: requirejsOptions
    });

    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.registerTask('default', [ 'requirejs' ]);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment