我同时使用grunt-contrib-less和grunt-contrib-watch。我的less任务使用文件数组格式来定义多个src和dest。我想从监视任务中引用这些相同的文件。是这样的:
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']
}
}
});
注:您可能喜欢阅读这些内容,以了解在模板中引用变量时发生了什么,以便稍后进行更高级的破解。