创建一个动态数组以在grunt concat中使用

时间:2015-02-09 23:07:23

标签: json gruntjs grunt-contrib-concat

我需要根据我已经定义了package.json的变量来连接一个set文件。

// package.json
...

"layouts": [
    { 
      "page": "home",
      "version": "a"
    },
    { 
      "page": "about",
      "version": "a" 
    },
    { 
      "page": "contact",
      "version": "b" 
    }
  ]

...

在grunt中,我将这些构建成一个JSON数组并将其泵入我的grunt-concat-contrib任务中的src参数。

// gruntfile.js
...

var package = grunt.file.readJSON('package.json'),
    targets = package.layouts,
    paths = [];

    for (var target = 0; target < targets.length; target++) {
        paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
    };

    var paths = JSON.stringify(paths);

    grunt.log.write(paths); // Writing this to console for debugging

    grunt.initConfig({
        concat: {
            build: {
                src: paths,
                dest: 'mysite/Code.php',
                options: {
                    separator: '?>\n\n'
                }
            }
        }
    });

...

我的问题是paths变量在分配给initConfig时在JSON.stringify(paths)内部无效。

如果我手动输入数组,如下所示,我将路径变量记录的位置复制到控制台,它可以正常工作!

var paths = ["layouts/home/a/*.php","layouts/about/a/*.php","layouts/contact/b/*.php"];

我错过了什么?

1 个答案:

答案 0 :(得分:0)

DERP。我修好了,我不需要JSON.stringify()数组。

最终工作gruntfile如下:

// gruntfile.js
...

var package = grunt.file.readJSON('package.json'),
    targets = package.layouts,
    paths = [];

for (var target = 0; target < targets.length; target++) {
    paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};

grunt.initConfig({
    concat: {
        build: {
            src: paths,
            dest: 'mysite/Code.php',
            options: {
                separator: '?>\n\n'
            }
        }
    }
});

...