如何让grunt.file.readJSON()等待,直到文件由另一个任务生成



我正在建立一系列与RequireJS .js编译器一起工作的grunt任务:1)生成目录中所有文件的.json文件列表2)从文件名中去掉"。js"(requires需要这个)3)使用grunt.file.readJSON()解析该文件,并将其用作我的requirejs编译任务中的配置选项。

下面是我的gruntfile.js中的相关代码:

module.exports = function (grunt) {
    grunt.initConfig({
    // create automatic list of all js code modules for requirejs to build
    fileslist: {
        modules: {
            dest: 'content/js/auto-modules.json',
            includes: ['**/*.js', '!app.js', '!libs/*'],
            base: 'content/js',
            itemTemplate: 't{' +
                'ntt"name": "<%= File %>",' +
                'ntt"exclude": ["main"]' +
                'nt}',
            itemSeparator: ',n',
            listTemplate: '[' +
                'nt<%= items %>n' +
                'n]'
        }
    },
    // remove .js from filenames in module list
    replace: {
       nodotjs: {
           src: ['content/js/auto-modules.json'],
           overwrite: true,
           replacements: [
                { from: ".js", to: "" }
           ]
       } 
    },
    // do the requirejs bundling & minification
    requirejs: {
        compile: {
            options: {
                appDir: 'content/js',
                baseUrl: '.',
                mainConfigFile: 'content/js/app.js',
                dir: 'content/js-build',
                modules: grunt.file.readJSON('content/js/auto-modules.json'),
                paths: {
                    jquery: "empty:",
                    modernizr: "empty:"
                },
                generateSourceMaps: true,
                optimize: "uglify2",
                preserveLicenseComments: false,
                //findNestedDependencies: true,
                wrapShim: true
            }
        }
    }
});
grunt.loadNpmTasks('grunt-fileslist');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['fileslist','replace', 'requirejs']);

我遇到了一个问题,如果"content/js/auto-modules. js "在加载配置文件时,文件不存在,file. readjson()立即执行,在文件存在之前,整个任务失败并抛出"Error: cannot read file "如果文件已经存在,一切都工作得很好。

我如何设置这个,以便任务配置等待该文件在第一个任务中创建,并在第二个任务中修改,然后再尝试加载&在第三个任务中解析JSON ?或者有另一种方法(也许使用不同的插件)在一个任务中生成json对象,然后将该对象传递给另一个任务?

我也有过类似的经历。

我正在尝试加载一些json配置,如:

conf: grunt.file.readJSON('conf.json'),

但是如果这个文件不存在,那么它会落在堆中,不做任何事情。

所以我做了以下操作来加载它并在它不存在时填充默认值:

    grunt.registerTask('checkConf', 'ensure conf.json is present', function(){
    var conf = {};
    try{
        conf = grunt.file.readJSON('./conf.json');    
    } catch (e){
        conf.foo = "";
        conf.bar = "";
        grunt.file.write("./conf.json", JSON.stringify(conf) );
    }
    grunt.config.set('conf', conf);
});

你仍然可能有一些时间问题,但这种方法可能会帮助有人读取json错误。

相关内容

最新更新