我正在尝试实现Grunt以自动化CSS合并和缩小的过程。我的文件夹结构:
的folder1
- sass
- css
文件夹2
- sass
- css
folder3
- sass
- css
folder4
- sass
- css
要求:单独地,当每个项目触发文件从eclipse中保存时,grunt任务正在正常运行。但是,我想要的是通过发出grunt命令来执行所有文件夹的缩小过程,即当我在cmd中键入“grunt”时,它应该遍历文件夹以为每个文件夹生成缩小的css。目前,它正在为每次迭代中的最后一个文件夹生成css,因为initconfig在循环内。
Gruntfile.js的简化版(仅提供相关代码):
module.exports = function(grunt) {
var tasks = [
'grunt-contrib-cssmin','grunt-sass'
];
tasks.forEach( function ( task ) {
grunt.loadNpmTasks( task );
});
var folder =['folder1', 'folder2', 'folder3', 'folder4'];
var source;
var csspath;
var destination;
for (var i = 0; i < folder.length; i ++ ) {
source=folder[i] + '/sass/*.scss';
csspath=folder[i] + '/css/';
destination=csspath + 'combined-styles.css';
grunt.initConfig({
config: {
destination: destination
},
sass: {
dist: {
files: {
'<%= config.destination %>' : [source]
}
},
},
cssmin: {
target: {
files: [{
expand: true,
cwd: csspath,
src: ['combined-styles.css'],
dest: csspath,
ext: '.min.css'
}]
}
}
});
grunt.task.registerTask(folder[i], ['sass','cssmin']);
}
grunt.task.registerTask('default', folder);
};
任何帮助都将受到高度赞赏,谢谢。
答案 0 :(得分:0)
我能够解决这个问题。以下是步骤:
从
更改了我的sass任务配置 files: {
'<%= config.destination %>' : [source]
}
到
files: [{
expand: true,
cwd: scsspath,
src: [source],
dest: csspath,
ext: '.css'
}]
(类似于cssmin)
使用grunt.config.set分别将sass和cssmin数组分配给sass和cssmin任务:
grunt.config.set(“sass”,sass);
grunt.config.set(“cssmin”,cssmin);
注册任务“sass”和“cssmin”
grunt.task.registerTask('default',['sass','cssmin']);
纠正Gruntfile.js:
module.exports = function(grunt) {
var tasks = [
'grunt-contrib-cssmin','grunt-sass'
];
tasks.forEach( function ( task ) {
grunt.loadNpmTasks( task );
});
var folder =['folder1', 'folder2', 'folder3', 'folder4'];
var source,csspath,scsspath;
var sass={};
var cssmin={};
for (var i = 0; i < folder.length; i ++ ) {
scsspath=folder[i] + '/sass/';
source='*.scss';
csspath=folder[i] + '/css/';
sass["folder"+i]= {
files: [{
expand: true,
cwd: scsspath,
src: [source],
dest: csspath,
ext: '.css'
}]
};
cssmin["folder"+i]= {
files: [{
expand: true,
cwd: csspath,
src: ['combined-styles.css'],
dest: csspath,
ext: '.min.css'
}]
};
}
grunt.config.set("sass", sass);
grunt.config.set("cssmin", cssmin);
grunt.task.registerTask('default', ['sass','cssmin']);
};