【问题标题】:Interpolated array in Grunt template is interpreted as a stringGrunt 模板中的插值数组被解释为字符串
【发布时间】:2014-06-26 21:53:32
【问题描述】:

上一篇:“为什么 Grunt 的 concat 任务不使用动态配置值?”

我正在尝试动态配置由 Grunt 连接的文件,这样做时我遇到了grunt-contrib-concat 插件似乎没有获取动态设置值的问题。起初我以为我做错了什么,但在创建自己的任务并使用相同的动态值之后,一切都按预期进行。那么问题来了,为什么 grunt concat 任务不使用相同的值?

重现该行为的 gruntfile 如下所示(要点:fatso83/73875acd1fa3662ef360)。

// Grunt file that shows how dynamic config (and option!) values
// are not used in the grunt-contrib-concat task. Run using 'grunt'
module.exports = function(grunt){

    grunt.initConfig({

        concat : {
            foo : {
                nonull : true,
                src: '<%= grunt.config.get("myfiles") %>',
                dest : 'outfile.txt'
            }
        },

        myTask : {
            bar : '<%= grunt.config.get("myfiles") %>'
        }
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-concat');

    grunt.registerMultiTask('myTask', function() {
        grunt.log.writeln('myTask:' + this.target + ' data=' + this.data);
    });

    grunt.registerTask('default', ['myTask','concat']);

    grunt.config.set('myfiles',['file1.txt', 'file2.txt'])
}

编辑:新线索: 经过几个小时无处可去后,我发现了这句话on Grunt's homepage:

nonull 如果设置为 true 则操作将包括非匹配 模式。结合 grunt 的 --verbose 标志,这个选项可以帮助 调试文件路径问题。

将它添加到配置中(上面已编辑以反映这一点)我收到了这条错误消息,它至少表明某些东西正在使用动态值做某事:

Running "concat:foo" (concat) task
>> Source file "file1.txt,file2.txt" not found.
Warning: Unable to write "outfile.txt/file1.txt,file2.txt" file 
(Error code: ENOTDIR). Use --force to continue.

在另一个任务myTask 中进行了更多调试后,我发现以this.data 发送到任务的数据是一个字符串值,而不是一个数组。考虑到我们进行字符串插值,这可能并不令人惊讶,但这与其他插值功能不一致。例如,&lt;%= otherTask.fooTarget.src %&gt; 会将其他任务的 src 属性作为数组值获取。

现在的问题实际上是如何避免将插值作为数组而不是字符串传递给 concat 任务?

【问题讨论】:

  • '&lt;%= grunt.config.get("myfiles") %&gt;' 是字符串而不是数组
  • 我也发现了!
  • @jantimon 但是 grunt 会对数组值(例如 )进行字符串插值,所以理想情况下它应该也能正常工作。

标签: gruntjs grunt-contrib-concat


【解决方案1】:

阅读Grunt source code后更新

在我发现问题在于我们的数组被解释为字符串后,我很快找到了related question with a solution that seemed promising。只需将插值后的数组字符串用大括号括起来,Grunt 就能找到文件!

不幸的是,我们正在有效创建的the globbing pattern 不保留指定的文件顺序。在上面的相关问题中,我posted a thorough explanation 说明了发生了什么以及在一般情况下如何解决它。

对于我的具体情况,我在配置对象中引用了一个字段,实际上不需要函数调用来检索它,因为它直接在模板自己的范围内可用!因此,我可以简单地调用&lt;%= myfiles %&gt;,而不是调用grunt.config.get('myfiles')。

对于上面的例子:

grunt.initConfig({

    concat : {
        foo : {
            nonull : true,
            src: '<%= myfiles %>',
            dest : 'outfile.txt'
        }
    },

    myTask : {
        bar : '<%= myfiles %>'
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 2013-10-13
    • 2022-01-10
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多