/css-mquery-packer

Simple media packer, merges same CSS media query rules into one via PostCSS

Primary LanguageJavaScriptMIT LicenseMIT

CSS Media Query Packer

Simple media packer, merges same CSS media query rules into one via PostCSS

npm GitHub Build Status Codacy Badge Codacy Badge Depfu

ABOUT

A straight forward example of what it does for you:

Before

.btn {
  display: inline-block;
}

@media screen and (max-width: 660px) {
  .btn {
    display: block;
    width: 100%;
  }
}

.wrapper {
  max-width: 1160px;
}

@media screen and (max-width: 660px) {
  .wrapper {
    max-width: 400px;
  }
}

After

.btn {
  display: inline-block;
}

.wrapper {
  max-width: 1160px;
}

@media screen and (max-width: 660px) {
  .btn {
    display: block;
    width: 100%;
  }
  .wrapper {
    max-width: 400px;
  }
}

INSTALL

npm install --save-dev css-mquery-packer

USAGE

Usage as a PostCSS plugin:

Gulp

gulpfile.js

const gulp = require('gulp');
const scss = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
const postssMergeRules = require('postcss-merge-rules');
const cssnano = require('cssnano');
const mqpacker = requrie('css-mquery-packer');

const processStyles = () => {
  const plugins = [
    mqpacker(),
    postssMergeRules(),
    cssnano({...}),
  ];

  return gulp.src('./path/to/src')
      .pipe(sourcemaps.init())
      .pipe(scss()).on('error', scss.logError)
      .pipe(postcss(plugins))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest('./path/to/dist'));
};

Webpack

webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack')
// ...
module: {
    rules: [
      {
        test: /\.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: true,
              reloadAll: true,
            },
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2,
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                require('postcss-import')(),
                require('css-mquery-packer')(),
                ...
              ],
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
    ],
  },
//...

postcss.config.js

module.exports = {
  plugins: {
    'css-mquery-packer': {},
    'postcss-merge-rules': {},
    cssnano: {
      preset: [
        'advanced',
        {
          normalizeWhitespace: false,
          discardUnused: false,
          mergeIdents: false,
          reduceIdents: false,
          autoprefixer: {},
        },
      ],
    },
  },
};

LICENSE

MIT