css autoprefixer with webpack

wrick17 picture wrick17 · Jun 24, 2016 · Viewed 33.5k times · Source

I have been trying to configure webpack with LESS and Autoprefixer, but autoprefixer does not seem to work. My css or less files are not autoprefixed. Example: display: flex stays display: flex

I have put my webpack config below:

var autoprefixer = require('autoprefixer');

module.exports = {
  entry: {
    bundle: "./index.jsx"
  },
  output: {
    path: __dirname,
    filename: "[name].js"
  },
  module: {
    loaders: [
      {
        test: /\.jsx$/,
        exclude: /(node_modules|bower_components)/,
        loaders: ['react-hot', 'babel-loader']
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader!less-loader")
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!postcss-loader")
      }

    ],
    postcss: function () {
      return [autoprefixer];
    }
  },
  plugins: [
    new webpack.BannerPlugin(banner),
    new ExtractTextPlugin("style.css")
  ],
  devtool: 'source-map',
  devServer: {
    stats: 'warnings-only',
  }
};

Answer

antoni picture antoni · Jul 15, 2018

As written in Autoprefixer documentation, "Autoprefixer uses Browserslist"

As per the Browserslist documentation, it is recommended to place the browserslist in package.json.

So here is another way to use autoprefixer with webpack:

install postcss-loader and autoprefixer:

npm i -D postcss-loader autoprefixer

webpack.config.js

module: {
  rules: [
    {
      test: /\.scss$/,
      exclude: /node_modules/, 
      use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader']
    },
    { 
      test: /\.css$/, 
      use: ['style-loader', 'css-loader', 'postcss-loader'] 
    },
    ...
  ]
}

As per postcss documentation, the postcss-loader should be placed after css-loader and style-loader, but before other preprocessor loaders like e.g sass|less|stylus-loader, if you use any.

package.json

"postcss": {
  "plugins": {
    "autoprefixer": {}
  }
},
"browserslist": [
  "last 2 version",
  "not dead",
  "iOS >= 9"
]

In this way, you don't need a postcss.config.js file.