postcss-remove-duplicate-mq v0.2.0
Remove Duplicate Media Queries
Table of Contents
What is it
This is a very simple PostCSS plugin that transforms this:
@media (min-width: 500px) and (max-width: 1000px) and (min-width: 500px) {
color: blue;
}
into this:
@media (min-width:500px) and (max-width:1000px) {
color: blue;
}
Install
npm install postcss-remove-duplicate-mq
Usage
Important: This plugin has a peerDependency on postcss-create-mq-ast. That
plugin creates the media query ast used by this plugin to remove the duplicates.
This also means that plugin must come before postcss-remove-duplicate-mq
.
const createMqAst = require('postcss-create-mq-ast'),
removeDuplicateMq = require('postcss-remove-duplicate-mq')
// 'createMqAst' _must_ come before 'removeDuplicateMq'
postcss([createMqAst(), removeDuplicateMq()])
.process(...)
Why create it
I use sass and write mixins such as
@include for-tablets {
color: blue;
}
where my for-tablets
mixin wraps the rule inside a media query.
There are times where it makes sense to nest these rules e.g.
@include for-phones-and-up {
color: blue;
@include for-phones {
background-color: red;
}
@include for-tablets {
background-color: green;
}
}
Sass resolves the would-be illegal syntax by concatenating all the nested rules
together using the and
operator. This concatenation results in duplicate
media queries which I want removed.
How it works
The code is very simple, so it may be easier just to give it a look.
It utilizes postcss-create-mq-ast to create the media query ast. It modifies the ast by removing all duplicate media features and gets the new media query string. Finally it replaces the params value with the new media query string.