Search code examples
lessgulpautoprefixer

How to combine postcss / autoprefixer with LESS


I have a site for which I use custom LESS stylesheets and they include Bootstrap LESS stylesheets. It is all compiled to the final style.css file with a style.css.map sourcemap.

This is how my Gulpfile looks:

var gulp = require('gulp');
var less = require('gulp-less-sourcemap');

var mySite = '.';

gulp.task('less', function () {
    gulp.src(mySite + '/css/**.less')
      .pipe(less())
      .pipe(gulp.dest(mySite + '/css'));
});

Now I'd like to add autoprefixer. This is what I've tried but it doesn't work:

var gulp = require('gulp');
var less = require('gulp-less-sourcemap');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer-core');

var mySite = '.';

gulp.task('less', function () {
    gulp.src(mySite + '/css/**.less')
      .pipe(less())
      .pipe(postcss([autoprefixer({ browsers: ['last 2 version'] })]))
      .pipe(gulp.dest(mySite + '/css'));
});

It's because I am piping the generated sourcemaps into postcss and it cannot handle it. So I've tried this:

var gulp = require('gulp');
var less = require('gulp-less-sourcemap');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer-core');

var mySite = '.';

gulp.task('less', function () {
    gulp.src(mySite + '/css/**.less')
      .pipe(less())
      .pipe(postcss([autoprefixer({ browsers: ['last 2 version'] })]))
      .pipe(gulp.dest(mySite + '/css'));


    gulp.src(mySite + '/css/**.css')
      .pipe(postcss([autoprefixer({ browsers: ['last 2 version'] })]))
      .pipe(gulp.dest(mySite + '/css'));
});

However, the prefixes are still not added. Maybe it's because the Bootstrap's CSS is already prefixed and it's somehow a problem for postcss?

How to make this work?


Solution

  • According to the Gulp-Less Readme,

    If you are using version 1.3.7 or higher you will have the ability to use a growing set LESS plugins, potentially simplifying your build steps.

    And the code they suggest using would look like this.

    var LessPluginAutoPrefix = require('less-plugin-autoprefix'),
        autoprefix= new LessPluginAutoPrefix({browsers: ["last 2 versions"]});
    
    
    gulp.src('./less/**/*.less')
      .pipe(less({
        plugins: [autoprefix]
      }))
      .pipe(gulp.dest('./public/css'));