Search code examples
csslessbuild-processgruntjs

Can I configure a grint-contrib-less task to compile into a parallel structure?


Currently we are using grunt-contrib-less to handle our LESS file compiling as a Grunt task. The less files are stored in a structure similar to this:

assets/
    styles/
        base.less
        client/
            client.less
            device/
                tablet.less
                phone.less

We have the following for our Grunt config:

less: {
    options: {
        paths: 'assets/',
        yuicompress: false,
        ieCompat: true,
        require: [
            'assets/styles/base.less'
        ]
    },
    src: {
        expand: true,
        cwd: 'assets/',
        src: [
            'styles/**/*.less'
        ],
        ext: '.css',
        dest: 'assets/'
    }
},

Currently this is installing all of the generated css files into the same directory as the original less file it came from. What we'd like to do is have them spit out into an /assets/css/ directory, but with the same relative structure. eg:

assets/
    css/
        base.css
        client/
            client.css
            device/
                tablet.css
                phone.css

Is there a grunt-contrib-less configuration that can accomplish this?


Solution

  • I was able to achieve the desired effect wit the following Gruntfile.js

    var path = require('path');
    
    module.exports = function(grunt) {
    
      grunt.initConfig({
        less: {
          options: {
            paths: 'assets/',
            yuicompress: false,
            ieCompat: true,
            require: [
              'assets/styles/base.less'
            ]
          },
          src: {
            expand: true,
            cwd: 'assets/',
            src: [
                'styles/**/*.less'
            ],
            ext: '.css',
            dest: 'assets',
            rename: function(dest, src) {
              return path.join(dest, src.replace(/^styles/, 'css'));
            }
          }
        },
      });
    
      grunt.loadNpmTasks('grunt-contrib-less');
    
    }
    

    Explanation

    Although it is not in the grunt-contrib-less docs there are a bunch more features available for files objects. I didn't realize there were this many until I was working on answering this question. The link for the docs on them is under resources.

    Resources

    Configuring tasks - Building the files object dynamically