简体   繁体   English

Grunt从文件重新加载JSON并更新任务选项

[英]Grunt reloading JSON from file and updating task options

I am using a configuration file with JSON format containing names of other files which I concatenate when one of the files is changed. 我正在使用JSON格式的配置文件,其中包含其他文件的名称,这些文件在更改其中一个文件时会串联在一起。 It works great so far, but I want to make the Grunt to reload the configuration file once it's changed (I remove or add something to the JSON) and update other task options (the concat task). 到目前为止,它运行良好,但是我想让Grunt在更改配置文件后重新加载配置文件(我在JSON中删除或添加了一些内容)并更新其他任务选项(concat任务)。

Here is my simplified Gruntfile.js: 这是我简化的Gruntfile.js:

module.exports = function(grunt) {
    function getModules() {
        var modules = grunt.file.readJSON('src/js/modules.json').modules;
        for ( var module in modules ) {
            if ( modules.hasOwnProperty(module) ) {
                modules[module] = 'src/js/modules/' + modules[module] + '.js';
            }
        }
        modules.push('src/js/scripts.js');
        return modules;
    }
    var modules = getModules();

    grunt.initConfig({
        concat: {
            options: {
                separator: ';',
            },
            dist: {
                src: modules,
                dest: 'assets/js/scripts.min.js',
            },
        },

        watch: {
            js_modules: {
                files: ['src/js/modules.json'],
                tasks: ['reload_modules', 'concat'],
                options: {
                    spawn: false,
                    livereload: true,
                },
            }
        }
    });

    grunt.registerTask('reload_modules', "Reload JavaScript modules", function() {
        modules = getModules();
    });
};

As you can see I have some attempt to solve my problem, but the updated modules variable is not used in the concat task. 如您所见,我已尝试解决问题,但是concat任务中未使用更新的modules变量。 The task uses the variable value loaded when the grunt default task is started. 该任务使用启动grunt默认任务时加载的变量值。

You should be able to overwrite the config using grunt.config.merge : 您应该能够使用grunt.config.merge覆盖配置:

var config = {
    // ...
};

grunt.config.init(config);

grunt.registerTask('reload_modules', "Reload JavaScript modules", function() {
    config.concat.options.dist.src = getModules();
    grunt.config.merge(config);
});

http://gruntjs.com/api/grunt.config http://gruntjs.com/api/grunt.config

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM