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

前端之家收集整理的这篇文章主要介绍了javascript – Grunt – 解析非字符串(例如数组)模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我在grunt配置中有一个变量,数组作为一个值.一个真实世界的例子是从 grunt-regarde插件中grunt.regarde.changed,其中列出了所有已更改的文件.

我想使用模板来解析该数组,这样我就可以(在这种情况下)复制更改的文件

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

在这种情况下,src得到的是一个逗号分隔的字符串而不是数组. Grunt的文件处理器不解析字符串,因此找不到src文件.

我不能删除模板周围的单引号,因为它是无效的JavaScript.

那么如何将该grunt.regarde.changed数组传递给src变量?

解决方法

问题很容易解决一旦你知道如何,只是几行代码,但是花了我一段时间,从Grunt源代码挖掘所有相关的信息,以了解该怎么做,所以裸露我而我带你穿过背景…

获取对配置对象的属性的一般方法是直截了当的:

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

这适用于在grunt.config对象上设置的所有属性,当然这包括传递给grunt.initConfig()的配置.这就是为什么您可以直接引用其他任务变量,例如<%= concat.typescriptfiles.dest%&gt ;,因为config对象中的所有属性都在模板自己的范围内. 技术上,当(LoDash)模板与选项对象(如果已定义)或grunt.config对象一起传递到模板处理器(LoDash’模板函数)时,这种扩展就会发生. 因此,这适用于在配置本身设置的值,或通过使用动态分配的值通过grunt.config.set().有关更多信息,请参阅API docs.

什么不能以同样的方式访问配置对象上不可用的值.看来,由于某种原因我不太清楚,所有其他价值观总是以字符串形式出现.无论您是直接访问还是通过方法调用,都会发生这种情况.例如,尝试通过grunt.config.get()获取对配置的数组的访问,从而获得一个字符串.

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

接受的答案以某种方式工作,但由于globbing语法,将由不保留文件顺序的glob()模块进行解析.这是我的建设的不 – 不.

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

  1. // This variable will be used twice to demonstrate the difference
  2. // between directly setting an attribute on the grunt object
  3. // and using the setter method on the grunt.config object
  4. var myFiles = ['c/file1.txt','a/file2.txt','b/file3.txt']
  5. module.exports = function(grunt){
  6.  
  7. grunt.initConfig({
  8.  
  9. debug : {
  10. using_attribute: {
  11. src : '<%= grunt.value_as_attribute %>' // will be a string
  12. },using_task: {
  13. src : '<%= value_by_setter %>' // will be an array
  14. },no_task_direct_setter: {
  15. src : '<%= value_by_setter_early %>' // will be an array
  16. }
  17. }
  18. });
  19.  
  20. grunt.registerTask('myValSetter',function() {
  21. grunt.config.set('value_by_setter',myFiles );
  22. });
  23.  
  24. // a task that will report information on our set values
  25. grunt.registerMultiTask('debug',function(){
  26. grunt.log.writeln('data.src: ',this.data.src);
  27. grunt.log.writeln('type: ',Array.isArray(this.data.src)? "Array" : typeof this.data.src);
  28. });
  29.  
  30. grunt.value_as_attribute = myFiles;
  31.  
  32. grunt.config.set('value_by_setter_early',myFiles );
  33.  
  34. grunt.registerTask('default',['myValSetter','debug']);
  35. }

这将输出

  1. $grunt
  2. Running "myValSetter" task
  3.  
  4. Running "debug:using_attribute" (debug) task
  5. data.src: c/file1.txt,a/file2.txt,b/file3.txt
  6. type: string
  7.  
  8. Running "debug:using_task" (debug) task
  9. data.src: [ 'c/file1.txt','b/file3.txt' ]
  10. type: Array
  11.  
  12. Running "debug:no_task_direct_setter" (debug) task
  13. data.src: [ 'c/file1.txt','b/file3.txt' ]
  14. type: Array
  15.  
  16. Done,without errors.

这个例子只是为了说明这个概念,但你应该可以轻松地将它自定义为你的实例:)

猜你在找的JavaScript相关文章