Search code examples
jsongruntjsuglifyjs

Grunt Uglify files from list in external document


I have a module system, which can be controlled via an admin UI, developers can enable or disable features and the task runner then takes care of preparing all UI assets into single files to load on the front-end.

With SASS, I can programmatically control the index.scss file to be compiled, meaning that this is simple enough - however, with JS I don't find the same option, yet.

The idea is to avoid any file duplication, manipulation or movement, to reduce complexity, avoid issues and also to speed up the task runner, which quickly gets bloated and slowed down.

As the process begins with a save routine, I can collect data about the current "active" modules and store this is any file format - json, csv, whatever - I would then like to load that config from the file in the Gruntfile - which might be continually watching ( in case it's a problem that config can only be loaded once? -- the data would need to be grabbed again fresh before each compilation ).

simple example:

*module.json

{"js":["modal.js","toast.js","tab.js","collapse.js","form.js","toggle.js","gallery.js","helper.js","scrollspy.js","scroll.js","lazy.js","javascript.js","comment.js","push.js","nprogress.js","consent.js","search.js","anspress.js","localize.js"]}

*Gruntfile.js

// ------- configuration ------- ##
module.exports = function(grunt) {

    grunt.initConfig({

        // load modules ##
        modules: grunt.file.readJSON('module.json'),

        'uglify': {
            // options etc ##
            files:{
                'library/asset/js/module.min.js' : '<%= modules.js %>'
            } 
         }

    });

    // Development Tasks ##
    grunt.registerTask( 
        'default'
        , [ 'uglify' ]
    );
}

This config runs, but does not load the data from JSON correctly - Grunt says:

Destination library/asset/js/module.min.js not written because src files were empty.

I know Grunt can read the JS, as I can do something like the following:

*terminal

$ grunt config
Running "config" task
["modal.js","toast.js","tab.js","collapse.js","form.js","toggle.js","gallery.js","helper.js","scrollspy.js","scroll.js","lazy.js","javascript.js","comment.js","push.js","nprogress.js","consent.js","search.js","anspress.js","localize.js"]
Done.

*Gruntfile.js

// load config ##
grunt.registerTask( 
    'config' 
    , function() {
        modules = grunt.file.readJSON('module.json')
        grunt.log.write(JSON.stringify( modules.js ) );
    }
);

Any ideas of pointers? Thanks!


Solution

  • The answer, was pretty simple - to include full paths to each "file" in the JSON, then Grunt parsed it withuot problems.