【问题标题】:Create a dynamic array for use in grunt concat创建用于 grunt concat 的动态数组
【发布时间】:2015-02-09 23:07:22
【问题描述】:

我需要根据我在 package.json 中定义的变量连接一组文件。

// 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 变量在分配给JSON.stringify(paths) 时在initConfig 内部不起作用。

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

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

我错过了什么?

【问题讨论】:

    标签: json gruntjs grunt-contrib-concat


    【解决方案1】:

    去吧。我修好了,我不需要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'
                }
            }
        }
    });
    
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多