Apply postcss plugins to webpack css asset
This webpack plugin gets css extracted by MiniCssExtractPlugin and applies postcss plugins to it.
Why?
If you use postcss-loader, not all its plugins are effective in file-by-file processing. For instance, css structural optimizations or media query packaging better apply to one css production file that can be generated by MiniCssExtractPlugin.
Installation
npm install --save-dev webpack postcss postcss-assets-webpack-plugin
Options
test
- regular expression for matching files returned from MiniCssExtractPlugin.
plugins
- array of postcss plugins
log
- boolean if plugin can print info to the console, true
by default
Usage
Simple example of webpack config that tranforms css-modules with less and postcss. Autoprefixer is used in development and production, mqpacker and csswring are used only for production build.
import webpack from 'webpack';
import csswring from 'csswring';
import mqpacker from 'mqpacker';
import autoprefixer from 'autoprefixer';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import PostCSSAssetsPlugin from 'postcss-assets-webpack-plugin';
const devMode = process.env.NODE_ENV !== 'production'
webpackConfig = {
<...>
postcss() {
return [autoprefixer({browser: 'last 2 version', cascade: false})]
},
module: {
rules: [
{
test: /\.less$/,
exclude: [/node_modules/],
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
minimize: false, // We use PostcssAssetsPlugin instead to minimize result chunks as a whole
localIdentName: '[name]_[local]_[sha512:hash:base64:3]',
},
},
{
loader: 'postcss-loader',
options: {
sourceMap: true,
},
},
{
loader: 'less-loader',
},
],
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
})
new PostCSSAssetsPlugin({
test: /\.css$/,
log: true,
plugins: [
// Pack same CSS media query rules into one media query rule
mqpacker,
// Minify CSS file with source maps. That’s only
csswring({preservehacks: true, removeallcomments: true}),
],
}),
],
};