Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate (and not compile) several less files into one using grunt

I'm having trouble finding a solution to this problem. I have a less file app.less that only consists of @import statements. Now I want to generate a single less file that includes all imported less files, because I want to send it to the client to compile it there (yes, I have my reasons to do that).

So the less file should not be compiled in the grunt build step, but only concatenated, so that the client doesn't have to load several less files. I feel that this is a usecase that should have appeared for others as well when compiling less on the client, but I couldn't find a single solution. I don't care if the concatenation happens with grunt-contrib-less or any other tool.

like image 260
Peter Avatar asked Dec 20 '22 01:12

Peter


2 Answers

LESS docs says:

Use @import (inline) to include external files, but not process them.

See: Import At-Rules and @import (inline)

You could create new file, for example concatenate.less and import .less files with inline keyword. Then if you process it, it will work exactly like concatenation, no CSS is processed out of it.

concatenate.less

@import (inline) "file1.less"
@import (inline) "file2.less"
@import (inline) "file3.less"

And use your Grunt task like you used to, just rename output file extension to .less for clarity. Tested it, should give you exactly what you wanted.

Nested imports

As @seven-phases-max pointed out, that nested imports would be problem in this case.

Solution would be grunt-includes.

  • Use grunt-includes with includeRegexp option to create files listed in concatenate.less with already imported LESS files to some other folder.
  • Change concatenate.less files paths to that folder.
  • Run your LESS compiling Grunt task normally.
like image 162
Rene Korss Avatar answered May 05 '23 05:05

Rene Korss


in case someone is working with gulp,

you can just create concatenate.less as @Rene Korss sugested, and use the same command as for compiling less.

Less outputs concatenate.css filename, which is misleading in our case, so I'm using gulp-rename to have filename named as I want.

var src = 'path-to-concatenate-less-file';
var destination = 'path-to-destination';
gulp.task('concatenate-styles', function () {
    var compile= gulp.src(src)
    .pipe(less())
    .pipe(rename('concatenate-all.less'))
    .pipe(gulp.dest(destination))
    .pipe(notify("Saved file: <%= file.relative %>!"));
    compile.on('error', console.error.bind(console));
    return compile;
});

Example of concatenate.less:

@import (inline) "general.less";
@import (inline) "typography.less";
like image 37
Angel M. Avatar answered May 05 '23 03:05

Angel M.