Search code examples
lessgulpgulp-less

gulp-less messes with global variable


I'm trying to pass a version string from gulp to less, as demonstrated in the following example project:

  • package.json:

    {
      "name": "webui",
      "version": "0.0.0",
      "private": true,
      "devDependencies": {
        "gulp": "^3.9.0",
        "gulp-less": "^3.0.5"
      }
    }
    
  • gulpfile.js:

    var gulp = require('gulp');
    var less = require('gulp-less');
    
    var LESS_PARAMS = {
      globalVars: {
        webUiVersion: '0.0.0'
      }
    };
    
    gulp.task('less', function() {
      return gulp.src('test.less')
        .pipe(less(LESS_PARAMS))
        .pipe(gulp.dest('.'))
    })
    
  • test.less:

    .test {
      background: url("test.jpg?v=@{webUiVersion}")
    }
    

When running gulp less, the generated test.cssfile looks like this:

.test {
  background: url("test.jpg?v=0 0");
}

As you can see, gulp-less somehow transformed 0.0.0 into 0 0. If I use a simple string without dots or 0, like 123asdf, the replacement works fine. Also, directly calling

lessc --global-var='webUiVersion="0.0.0"' test.less

on the command line produces the desired result.

So my questions are:

  • Is this intentional behaviour or a bug?
  • Is there a way to work around this issue?

Solution

  • I've found a way to fix this issue: The trick is to enclose the string that should be passed to less in quotes, that is writing webUiVersion: '"0.0.0"' instead of webUiVersion: '0.0.0' in gulpfile.js.

    The reason for this has been pointed out by seven-phases-max below: The value of webUiVersion is directly passed to less. Without the quotes, 0.0.0 is parsed as two numbers, namely 0.0 followed by .0, which results in 0 0 in the generated CSS.