Search code examples
cssgruntjslessgrunt-contrib-less

How to set resolve path for image-width?


I have a LESS file that refers to an absolute location (it needs to be absolute or grunt-usemin won't parse it properly), but this causes the less compiler to not be able to resolve the image when processing image-width().

/client/app/app.less

// logo is located at /client/assets/images/ but "/client" is the 
// web root, which is why the absolute reference is "/assets/images"
@logo-url: '/assets/images/web-header-111_253x45.gif';
@logo-width: image-width(@logo-url);
@logo-height: image-height(@logo-url);

.web-header {
    width: @logo-width;
    height: @logo-height;
    background: url(@logo-url);
}

/gruntfile.js

  grunt.initConfig({

    /* TRIMMED */

    less: {
      options: {
      },
      server: {
        files: [{
          src: ['client/app/app.less'],
          dest: '.tmp/app/app.css'
        }]
      }
    }

    /* TRIMMED */
  });

The above will throw the following build error:

Warning: Running "less:server" (less) task
>> RuntimeError: error evaluating function `image-width`: ENOENT, no such file or directory 'C:\git\www-project\client\app\assets\images\web-header-111_2
53x45.gif' in client\app\app.less on line 26, column 14:
>> 25 @logo-url: '/assets/images/web-header-111_253x45.gif';
>> 26 @logo-width: image-width(@logo-url);
>> 27 @logo-height: image-height(@logo-url);
Warning: Error compiling client/app/app.less Use --force to continue.

Aborted due to warnings.

Question: What can I set to make image-width(...) resolve relative to the C:\git\www-project\client directory rather than the directory containing app.less?


Solution

  • If I set both an absolute URL path & calculate a relative file path, then the image-width(...) path can be resolved with no problem.

    // logo is located at /client/assets/images/ but "/client" is the 
    // web root, which is why the absolute reference is "/assets/images"
    @root: '..';
    @logo-url: '/assets/images/web-header-111_253x45.gif';
    @logo-path: '@{root}@{logo-url}';
    @logo-width: image-width(@logo-path);
    @logo-height: image-height(@logo-path);
    
    .web-header {
        width: @logo-width;
        height: @logo-height;
        background: url(@logo-url);
    }