Css source map example using gulp-sourcemaps

If you are concatenating multiple css files into once css file, it is useful to have sourcemap in your combined css file in development environment. That way chrome developer tools can show the correct source file while debugging. Here is quick example on Ubuntu Linux which generates css sourcemap and then we will see it working in Chrome. In case you are not familiar with gulp, you can visit Gulp quick start tutorial

Files used

These are the files used in this tutorial. Create these files in a proj1 directory inside css folder.

.foo {
  width: 20px;

.bar {
  width: 30px;

Genereting sourcemap

  1. Create gulpfile.js inside proj1 directory with the following content.
    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var sourcemaps = require('gulp-sourcemaps');
    gulp.task('css', function() {
      return gulp.src(['./css/file1.css', './css/file2.css'])
  2. Run the following on command line to generate all.css with source map.

    $ gulp css
    [12:27:59] Using gulpfile ~/tmp/proj1/gulpfile.js
    [12:27:59] Starting 'css'...
    [12:27:59] Finished 'css' after 39 ms
  3. Look at the content of all.css

    $ cat dest/all.css
    .foo {
      width: 20px;
    .bar {
      width: 30px;
    /*# sourceMappingURL=all.css.map */

    And all.css.map

    $ cat dest/all.css.map 
    {"version":3,"sources":["file1.css","file2.css"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;ACHA;AACA;AACA;AACA","file":"all.css","sourcesContent":[".foo {\n  width: 20px;\n}\n",".bar {\n  width: 30px;\n}\n"],"sourceRoot":"/source/"}
  4. The comment /*# sourceMappingURL=all.css.map */ tells the browser the location of source map. And sourcemap file all.css.map contains the actual source mapping.

Viewing source css file in chrome

  1. Create a test html file which uses all.css as shown below.
    <link rel='stylesheet' id='style-css' href='http://dev.infoheap.com/dest/all.css' type='text/css' media='all' />
    <div class="foo">
  2. Now try to inspect the div element in Chrome developer tools. You should be able to see style with original source files (e. g. file1.css) as shown below:
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments