说我在grunt配置中有一个变量,数组作为一个值.一个真实世界的例子是从
grunt-regarde插件中grunt.regarde.changed,其中列出了所有已更改的文件.
我想使用模板来解析该数组,这样我就可以(在这种情况下)复制更改的文件:
- copy: {
- staticWeb: {
- src: '<%= grunt.regarde.changed %>',dest: 'someDir'
- },
在这种情况下,src得到的是一个逗号分隔的字符串而不是数组. Grunt的文件处理器不解析字符串,因此找不到src文件.
我不能删除模板周围的单引号,因为它是无效的JavaScript.
那么如何将该grunt.regarde.changed数组传递给src变量?
解决方法
问题很容易解决一旦你知道如何,只是几行代码,但是花了我一段时间,从Grunt源代码挖掘所有相关的信息,以了解该怎么做,所以裸露我而我带你穿过背景…
- <%= some.property %> // fetches grunt.config.get('some.property')
这适用于在grunt.config对象上设置的所有属性,当然这包括传递给grunt.initConfig()的配置.这就是为什么您可以直接引用其他任务变量,例如<%= concat.typescriptfiles.dest%> ;,因为config对象中的所有属性都在模板自己的范围内. 技术上,当(LoDash)模板与选项对象(如果已定义)或grunt.config对象一起传递到模板处理器(LoDash’模板函数)时,这种扩展就会发生. 因此,这适用于在配置本身设置的值,或通过使用动态分配的值通过grunt.config.set().有关更多信息,请参阅API docs.
什么不能以同样的方式访问配置对象上不可用的值.看来,由于某种原因我不太清楚,所有其他价值观总是以字符串形式出现.无论您是直接访问还是通过方法调用,都会发生这种情况.例如,尝试通过grunt.config.get()获取对配置的数组的访问,从而获得一个字符串.
接受的答案以某种方式工作,但由于globbing语法,将由不保留文件顺序的glob()模块进行解析.这是我的建设的不 – 不.
解决方法,以防您要使用的阵列在配置对象上不可用,是通过中间任务将其添加到配置.像下面这样的东西应该有效:
- // 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','b/file3.txt' ]
- type: Array
- Running "debug:no_task_direct_setter" (debug) task
- data.src: [ 'c/file1.txt','b/file3.txt' ]
- type: Array
- Done,without errors.
这个例子只是为了说明这个概念,但你应该可以轻松地将它自定义为你的实例:)