如何配置grunt-contrib-less以生成与Chrome DevTools兼容的源映射?

Ale*_*ias 11 less google-chrome-devtools source-maps grunt-contrib-less

问题标题几乎说明了一切.我不知道如何配置现在支持源映射的grunt-contrib-less任务.我的预期结果是让Chrome DevTools CSS检查器指向Less规则.如果可能的话,理想的情况是源映射在同一个输出的CSS文件中内联,以避免使用单独的源映射文件混乱我的工作区.

谢谢

小智 12

这是我的gruntfile.js,它的工作原理.

更新为grunt-contrib-less v0.9.0是很重要的.使用"XXX.css.map"而不是"XXX.map"也很重要.并且在给出了适当的sourcebasepath之后它工作了.下面我将发布结果.map文件的摘录.

gruntfile.js

module.exports = function(grunt) {
  grunt.initConfig({
    less: {
      development: {
        options: {
          compress: false,
          yuicompress: false,
          optimization: 2,
          sourceMap: true,
          sourceMapFilename: "assets/style/bootstrap.css.map",
          sourceMapBasepath: "assets/style/"
        },
        files: {
          // target.css file: source.less file
          "assets/style/bootstrap.css": "assets/style/bootstrap.less"
        }
      }
    },
    watch: {
      styles: {
        // Which files to watch (all .less files recursively in the less directory)
        files: ['assets/style/theme/**/*.less'],
        tasks: ['less'],
        options: {
          nospawn: true
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['watch']);
};
Run Code Online (Sandbox Code Playgroud)

这是使用lessc生成的.map文件的摘录,当然可以使用:

{"version":3,"file":"bootstrap.css","sources":["theme/page-welcome.less","bootstrap-2.3.2/mixins.less"...
Run Code Online (Sandbox Code Playgroud)

这是使用grunt-contrib-less 0.9.0生成的.map文件的摘录,它也有效:

{"version":3,"sources":["theme/page-welcome.less","bootstrap-2.3.2/mixins.less","theme/page-work.less"...
Run Code Online (Sandbox Code Playgroud)

亲切的问候,斯蒂芬


小智 2

首先,您需要确保 grunt-contrib-less 正在运行支持源映射的版本。最新版本是 0.9.0,因此请更新 package.json 文件中使用的版本,如下所示:

"dependencies" : {
    ...[other dependencies]...
    "grunt-contrib-less" : "0.9.0"
}
Run Code Online (Sandbox Code Playgroud)

现在在命令行中,调用npm install以安装更新。


接下来,在 Gruntfile.js 中,为您的项目配置源映射。

您可以按照此处的指南进行操作:http://robdodson.me/blog/2012/12/28/debug-less-with-chrome-developer-tools/或此处: http: //roots.io/using-less- source-maps/,但这是一个示例配置:

    less : {
        development : {
            options : {
                strictImports : true,
                sourceMap: true,
                sourceMapFilename: '../css/common.css.map',
                sourceMapURL: 'http://localhost/css/common.css.map'
            },
            files : {
                '../css/common.css' : '../less/common.less'
            }
        },
    },
Run Code Online (Sandbox Code Playgroud)

关键是确保您使用的 sourceMapURL 是可以在浏览器中打开的实际 URL。