我同时使用 grunt-contrib-less 和 grunt-contrib-watch。我的 less 任务使用文件数组格式来定义多个 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 分开。
有没有更优雅的方法来完成这个?
最佳答案
我confirmed 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
关于javascript - grunt watch - 使用文件数组格式作为源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436631/