簡體   English   中英

grunt watch - 使用文件數組格式作為源

[英]grunt watch - use files array format as source

我正在使用grunt-contrib-less和grunt-contrib-watch。 我的少任務使用文件數組格式來定義多個src和dest。 我想從watch任務中引用那些相同的文件。 像這樣:

grunt.initConfig({
  less: {
    build: {
      files: [
        {src: 'src/aa.less', dest: 'dest/a.css'},
        {src: 'src/aa1.less', dest: 'dest/a1.css'}
      ]
    }
  },
  watch: {
    less: {
      files: '<%= less.build.files %>',
      tasks: ['less']
    }
  }
});

該下划線模板有效,但watch無法處理文件數組格式,它只接受文件輸入為字符串或字符串數​​組。 這是我嘗試過的:

  • '<%= less.build.files.src %>'不起作用,因為less.build.files是一個數組,而不是一個對象。

  • '<%= _(less.build.files).pluck("src").value() %>'不起作用,因為即使它生成了正確的文件列表,它也會解析為單個字符串'src/aa.less,src/aa1.less' ,不是數組。

  • '{<%= _(less.build.files).pluck("src") %>}'確實有效,如https://stackoverflow.com/a/21608021/490592所示 ,但感覺不到對。 我正在嘗試定位一組特定的文件,而不是整個項目目錄中的模式匹配。

  • grunt.config.set('watch.less.files', _(grunt.config.get('less.build.files')).pluck('src').value()); 有效,但必須與initConfig分開。

是否有更優雅的方式來實現這一目標?

確認 grunt-contrib-watch不支持文件數組格式。 我決定使用上面提到的grunt-config-set技術。

即使watch不支持文件數組格式,我也確保我的自定義任務與它兼容,因此我不必使用我的問題中的變通方法。 我附上了一個例子。 對於只讀任務,我添加了一個useDest選項,因此可以將它們配置為在dest而不是src上運行。 當您想要將一個任務“管道”到另一個任務時,這會有所幫助。

module.exports = function (grunt) {

  grunt.registerMultiTask('example', 'Example read-only task', function () {
    var options = this.options({
          useDest: false, // When true, operate on dest files, instead of src
        });
        files = this.files.map(function (file) {
          return { src: (options.useDest) ? [file.dest] : file.src }
        });
    files.forEach(function (file) {
      grunt.log.writeln('Source: ' + grunt.log.wordlist(file.src));
    });
  });

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

  grunt.initConfig({
    concat: {
      build: {
        files: [
          { src: 'node_modules/grunt/lib/grunt/*.js', dest: 'lib.js' },
          { src: 'node_modules/grunt/internal-tasks/*.js', dest: 'tasks.js' }
        ]
      }
    },
    example: {
      build: {
        options: {
          useDest: true
        },
        files: '<%= concat.build.files %>'
      }
    }
  });

};

任務將輸出:

Running "example:build" (example) task
Source: lib.js
Source: tasks.js

我不明白為什么你沒有簡單地將文件部分重構為變量? 以下實現了“喜歡從監視任務中引用相同文件”的目標。

var yourFiles = [
    {src: 'src/aa.less', dest: 'dest/a.css'},
    {src: 'src/aa1.less', dest: 'dest/a1.css'}
];

grunt.initConfig({
    less: {
        build: {
            files: yourFiles 
        }
    },
    watch: {
        less: {
            files: yourFiles 
            tasks: ['less']
        }
    }
});

PS你可能喜歡閱讀這篇文章來了解在引用模板中的變量時會發生什么,以便稍后進行一些更高級的黑客攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM