Search code examples
gruntjsgrunt-contrib-less

Grunt task with grunt-contrib-less - how to compile multiple stylesheets while maintaining their original .less file name


I'm building a website with Bootstrap using less. I use grunt to automate the tasks.

In my gruntfile.js I have this part:

less: {
  compileCore: {
    options: {
      strictMath: true,
      sourceMap: true,
      outputSourceFiles: true,
      sourceMapURL: '<%= pkg.name %>.css.map',
      sourceMapFilename: 'dist/css/<%= pkg.name %>.css.map'
    },
    src: 'less/bootstrap.less',
    dest: 'dist/css/<%= pkg.name %>.css'
  },
  compileBrandingStyles: {
    options: {
      strictMath: true,
      sourceMap: false,
      outputSourceFiles: false
    },
    src: 'less/branding/**/*.less',
    dest: 'dist/css/<%= what do I put here? %>.css'
  }
},

In "compileBrandingStyles" I would like to fetch all *.less files in a folder and compile them into seperate css files with their original file names. No concatenation.

In the folder: less/branding I have x number of .less files:

theme-1.less
theme-2.less
theme-3.less
theme-4.less

I would like to output them in the dist/css/ folder like this:

theme-1.css
theme-2.css
theme-3.css
theme-4.css

So how should I write this part to keep their file names?

dest: 'dist/css/<%= what do I put here? %>.css'

Solution

  • Reconfigure your compileBrandingStyles Target to this instead:

    // ...
    compileBrandingStyles: {
        options: {
            strictMath: true,
            sourceMap: false,
            outputSourceFiles: false
        },
        files: [{
            expand: true,
            cwd: 'less/branding/',
            src: ['**/*.less'],
            dest: 'dist/css/',
            ext: '.css'
        }]
    }
    

    See further info on this in the grunt docs.


    EDIT

    If you don't' want the sub folders included in the destination folder use flatten.

    // ...
    compileBrandingStyles: {
        options: {
            strictMath: true,
            sourceMap: false,
            outputSourceFiles: false
        },
        files: [{
            expand: true,
            cwd: 'less/branding/',
            src: ['**/*.less'],
            dest: 'dist/css/',
            ext: '.css',
            flatten: true // <-- Remove all path parts from generated dest paths.
        }]
    }