How can I make 'grunt less' automatically run autoprefixer?

mikemaccana picture mikemaccana · Dec 4, 2013 · Viewed 7.5k times · Source

I have a working Gruntfile with less and autoprefixer. I also have 'grunt watch' working fine.

Before I was using autoprefixer, I was using less mixins for vendor prefixes. Running 'grunt less' would build working CSS with all my prefixes.

Now I have autoprefixer, but if I want to do a once-off build of my styles, I now have to run 'grunt less' then 'grunt autoprefixer' to get working CSS with prefixes.

How can I modify 'grunt less' so it build working, prefixes less again?

I've read the docs, and I know I could add an additional task to do both these things. However:

  • 'grunt less' now doesn't have usable output. A task should always produce usable output.
  • I don't want to have to tell other people that 'grunt less' doesn't produce usable output
  • An additional task should not be required to replace one that doesn't work

I.e., I just want grunt less to produce working CSS (with prefixes).

module.exports = function(grunt) {

  // Load Grunt tasks declared in the package.json file
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // Configure Grunt
  grunt.initConfig({

    less: {
      development: {
        options: {
          paths: ["./less"],
          yuicompress: false
        },
        files: {
          "./public/css/style.css": "./public/less/style.less"
        }
      }
    },

    autoprefixer: {
      development: {
        browsers: ['last 2 version', 'ie 9'],
        expand: true,
        flatten: true,
        src: 'public/css/*.css',
        dest: 'public/css'
      }
    },

    watch: {
      less: {
        files: ["./public/less/*"],
        tasks: ["less", "autoprefixer:development"],
        options: {
          livereload: true
        }
      }
    },

  });


};

Answer

Dunaevsky Maxim picture Dunaevsky Maxim · Feb 24, 2015

For using autoprefixer as plugin for LESS, you must install npm-package less-plugin-autoprefix:

npm install grunt-contrib-less less-plugin-autoprefix --save-dev

Gruntfile.js

module.exports = function(grunt) {
  "use strict";
  var gruntConfig = {
    less : {
      options : {
        plugins : [ new (require('less-plugin-autoprefix'))({browsers : [ "last 2 versions" ]}) ]
      },
      main : {
        files: {
          'src/css/desktop/bootstrap-theme.css' : 'src/less/desktop/bootstrap-theme.less',
          'src/css/desktop/company.css' : 'src/less/desktop/company.less',
          'src/css/desktop/index.css' : 'src/less/desktop/index.less',
          'src/css/desktop/login.css' : 'src/less/desktop/login.less'
        }
      }
    }
  };

  grunt.initConfig(gruntConfig);
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.registerTask('default', [ 'less' ]);
};