我有多个.less文件,我想要处理它们匹配的.css,每个文件的sourceMaps都在与源相同的文件夹中。
这有多难?
我没有任何问题,直接用较少但不能解决如何在grunt-contrib-less中执行此操作,因为它似乎希望sourceMapFilename是单个硬编码值。
这是我的gruntfile:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
watch: {
options: {
livereload: true,
},
css: {
files: ['./core/theme/**/*.less'],
tasks: ['less'],
options: {
spawn: false
},
},
},
less: {
all: {
src: ['./core/theme/**/*.less'],
expand: true,
dest: "./core/theme/",
options:{sourceMap:true},
rename:function (dest, src) {
return src.substring(0, src.lastIndexOf('.'))+'.css';
}
},
}
});
// on watch events configure less:all to only run on changed file
grunt.event.on('watch', function(action, filepath) {
grunt.config('less.all.src', filepath);
});
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-less");
grunt.registerTask("default", ["less"]);
};
TIA
答案 0 :(得分:1)
您可以定义多个目标。每个目标编译一个特定的较少文件。 假设您有一个合理/有限的较少文件列表要编译(< 10?)。 http://gruntjs.com/configuring-tasks#task-configuration-and-targets
定义常见的任务级选项(减少编译选项),然后定位特定选项(sourceMapFilename& sourceMapURL)。 http://gruntjs.com/configuring-tasks#options
我不确定如何动态设置sourceMapFilename,但我稍后会对此进行研究。如果您正在编译许多LESS文件(> 10?),那将是必要的。
答案 1 :(得分:0)
目前grunt-contrib-less没有这样的选项,请参阅:https://github.com/gruntjs/grunt-contrib-less/issues/89
您可以使用grunt.file获取较少文件的列表,而不是自动生成每个文件的任务,另请参阅:Compile LESS to multiple CSS files, based on variable value
<强> Gruntfile.js:强>
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
});
var allTaskArray = [];
var tasks = {};
grunt.file.recurse('less/', function(abspath, rootdir, subdir, filename)
{
if(filename.match(/\.less$/g)){
var name = filename.substring(0, filename.lastIndexOf('.'));
tasks[name] = {options: {sourceMap:true},files:{} };
tasks[name]['options']['sourceMapFilename'] = 'dist/' + name + '.map.css';
tasks[name]['files']['dist/' + name + '.css'] = abspath;
allTaskArray.push('less:' + name);
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.config('less',tasks);
grunt.registerTask( 'default', allTaskArray );
};
当你的文件结构如下所示:
less
├── less2
│ └── main2.less
└── main.less
运行grunt
将导致:
Running "less:main2" (less) task
File dist/main2.map.css created.
File dist/main2.css created: 24 B → 66 B
Running "less:main" (less) task
File dist/main.map.css created.
File dist/main.css created: 24 B → 65 B
请注意,您还可以动态添加监视任务,如下所示:
grunt.loadNpmTasks('grunt-contrib-watch');
var watch = {
options: {
livereload: true,
},
css: {
files: ['./less/**/*.less'],
tasks: [],
options: {
spawn: false
},
}
};
watch['css']['tasks'] = allTaskArray;
grunt.config('watch',watch);