Grunt - 解析非字符串(例如数组)模板

2023-11-24

假设我的 grunt 配置中有一个变量,其中包含一个数组作为值。一个现实世界的例子是grunt.regarde.changed来自咕噜注视插件,列出所有已更改的文件。

我想使用模板解析该数组,以便我可以(在本例中)复制更改的文件:

  copy: {
    staticWeb: {
      src: '<%= grunt.regarde.changed %>',
      dest: 'someDir'
    },

What src在这种情况下, gets 是 a 是单个逗号分隔的字符串而不是数组。 Grunt 的文件处理器不会解析该字符串,因此无法找到 src 文件。

我无法删除模板周围的单引号,因为这样它就是无效的 JavaScript。

那么我该如何通过它grunt.regarde.changed数组到src多变的?


一旦你知道如何解决,这个问题就很容易解决,只需几行代码,但我花了很长时间才从 Grunt 源代码中挖掘出所有相关信息,以便了解该怎么做,所以请耐心等待当我带你了解背景时......


取得财产的一般方式配置对象很简单:

<%= some.property %> // fetches grunt.config.get('some.property')

这适用于已设置的所有属性grunt.config对象,其中(当然)包括传递到的配置grunt.initConfig()。这就是为什么您可以直接引用其他任务变量,例如<%= concat.typescriptfiles.dest %>,因为配置对象中的所有属性都在模板自己的范围内。

从技术上讲,当 (LoDash) 模板与以下任意一个一起传递时,就会发生这种扩展options对象(如果已定义)或grunt.config模板处理器的对象(LoDash'template功能)。

因此,这适用于在配置本身中设置的值,或者通过使用动态分配的值grunt.config.set()。请参阅API docs了解更多信息。

不以同样的方式工作的是访问配置对象上不可用的值。似乎出于某种我不太确定的原因,所有其他值总是以字符串结束。无论您是直接访问它们还是通过方法调用访问它们,都会发生这种情况。例如尝试通过以下方式访问配置上的数组grunt.config.get()给你一个字符串。

保留文件顺序问题的解决方法

接受的答案以某种方式起作用,但由于通配语法,它将由glob() module 不保留文件顺序。这对于我的构建来说是一个禁忌。

如果您要使用的数组在配置对象上不可用,解决方法是通过中间任务将其添加到配置中。像下面这样的东西应该有效:

// This variable will be used twice to demonstrate the difference
// between directly setting an attribute on the grunt object
// and using the setter method on the grunt.config object
var myFiles = ['c/file1.txt', 'a/file2.txt', 'b/file3.txt']
module.exports = function(grunt){

    grunt.initConfig({

        debug : {
            using_attribute: {
                src : '<%= grunt.value_as_attribute %>' // will be a string
            },
            using_task: {
                src : '<%= value_by_setter %>' // will be an array
            },
            no_task_direct_setter: {
                src : '<%= value_by_setter_early %>' // will be an array
            }
        }        
    });

    grunt.registerTask('myValSetter', function() {
        grunt.config.set('value_by_setter', myFiles );
    });

    // a task that will report information on our set values
    grunt.registerMultiTask('debug', function(){
        grunt.log.writeln('data.src: ', this.data.src);
        grunt.log.writeln('type: ', Array.isArray(this.data.src)? "Array" : typeof this.data.src);
    });

    grunt.value_as_attribute = myFiles;

    grunt.config.set('value_by_setter_early', myFiles );

    grunt.registerTask('default',['myValSetter', 'debug']);
}

这将输出

$ grunt
Running "myValSetter" task

Running "debug:using_attribute" (debug) task
data.src:  c/file1.txt,a/file2.txt,b/file3.txt
type:  string

Running "debug:using_task" (debug) task
data.src:  [ 'c/file1.txt', 'a/file2.txt', 'b/file3.txt' ]
type:  Array

Running "debug:no_task_direct_setter" (debug) task
data.src:  [ 'c/file1.txt', 'a/file2.txt', 'b/file3.txt' ]
type:  Array

Done, without errors.

这个示例只是为了说明这个概念,但您应该能够轻松地将其自定义到您的实例:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Grunt - 解析非字符串(例如数组)模板 的相关文章

随机推荐