Using LESS Source Maps

The adoption of CSS preprocessors has grown a lot over the past few years. One of the major complaints that people have voiced regarding preprocessors is the inability to see where your CSS rules come from when inspecting elements with developer tools.

Source maps allow you to view the original source file and line numbers from your CSS even when you're loading the generated CSS file.

Source maps support has been available for Sass, but LESS only recently added source maps support with the release of LESS 1.5.0.

Enabling Source Maps in Roots

Up until recently Roots was using grunt-recess to compile LESS to CSS. Since the RECESS project hasn't updated and we wanted to take advantage of source maps, we've replaced grunt-recess with grunt-contrib-less. grunt-contrib-less comes with LESS 1.5.0 and allows us to enable source maps with ease. The updated LESS task in the Roots Gruntfile.js looks like:

less: {
  dist: {
    files: {
      'assets/css/main.min.css': [
        'assets/less/app.less'
      ]
    },
    options: {
      compress: true,
      // LESS source maps
      // To enable, set sourceMap to true and update sourceMapRootpath based on your install
      sourceMap: false,
      sourceMapFilename: 'assets/css/main.min.css.map',
      sourceMapRootpath: '/app/themes/roots/'
    }
  }
}

Enabling the source map is easy. Update the task to set sourceMap to true and then update the sourceMapRootpath to reflect the root relative path to the theme folder in your WordPress installation.

A typical path would be '/wp-content/themes/roots/' — the default of '/app/themes/roots/' comes from our recommendation of using Composer to manage WordPress.

The source map is saved as assets/css/main.min.css.map, and main.min.css is updated with the following at the end of the file:

/*# sourceMappingURL=/app/themes/roots/assets/css/main.min.css.map */

This enables developer tools to map calls back to their location in original source files. Once you've updated your Gruntfile.js and ran grunt, inspect an element on your site. You'll now be able to see the original source files and line numbers:

LESS source maps