来自外部文件的 Grunt 服务器任务配置

Grunt server task config from external files

我是 运行 一个 Angular.js 应用程序,所有任务管理都是用 grunt 完成的,现在我有三个组件正在实时重新加载,bower_components 、发票和用户,最终它们的数量会增加,所以我想知道是否有办法调用 components.json 之类的外部文件并遍历其 n 个成员。这是我的代码:

// The grunt server settings
connect: {
    options: {
        port: 9000,
        hostname: 'localhost',
        livereload: 35729
    },
    livereload: {
        options: {
            open: true,
            middleware: function (connect) {
                return [
                    connect.static('.tmp'),
                    connect().use(
                        '/bower_components',
                        connect.static('./bower_components')
                    ),
                    connect().use(
                        '/invoices',
                        connect.static(invoicesAppPathConfig.root)
                    ),
                    connect().use(
                        '/users',
                        connect.static(usersAppPathConfig.root)
                    ),
                    connect.static(secureAppPathConfig.app)
                ];
            }
        }
    },
    dist: {
        options: {
            open: true,
            base: '<%= main.dist %>'
        }
    }
}

我已经创建了 component.json 文件:

{"data":[
    {
        "resource":"/bower_components",
        "config":"./bower_components"
    },
    {
        "resource":"/invoices",
        "config":"invoicesAppPathConfig.root"
    },
    {
        "resource":"/users",
        "config":"usersAppPathConfig.root"
    }
]}

并且在 Gruntfile.js 中我创建了这个变量,考虑到我需要迭代数据的内容:

var components = require('./components.json');
var data = components.data;

现在我有一个问题,我该如何在代码中做到这一点?

middleware: function (connect) {
    return [
        connect.static('.tmp'),
        // Here comes the data iteration
        connect.static(secureAppPathConfig.app)
    ];
}

提前致谢。

当然可以:

grunt.initConfig({
    components: grunt.file.readJSON('components.json'),
    [...]
});

更多info on grunt.file here

您也可以要求它:

var components = require('./components.json');

创建下一个变量:

var components = require('./components.json');
var data = components.data;
var arrayComponents = [];

然后在 livereload 的选项中迭代 json 数据并将其添加到 arrayComponents:

middleware: function (connect){
    arrayComponents.push(connect.static('.tmp'));
    // The modules to be watched are added
    for(var i in data){
        arrayComponents.push(connect().use(data[i].resource, connect.static(data[i].config)));
    }
    arrayComponents.push(connect.static(secureAppPathConfig.app));
    return arrayComponents;
}

可行,但可能不是最优雅的解决方案。