media-query-parser
- Create a JS object from a CSS media queries
- Create a CSS media query from a JS object
- Returns a ParserError for invalid CSS media queries
- Spec-compliant - https://www.w3.org/TR/mediaqueries-5/
- All valid queries parsed
e.g. (100px < width < 200px)
- Zero-dependencies
- Well tested - every single line
- TypeScript friendly
Try it!
Why?
Other CSS parsers (e.g. css-tree and postcss) do not support all media query syntax out of the box.
Further, the only other media query parser that I'm aware of is postcss-media-query-parser
- which
is specific to postcss and doesn't parse newer syntax like range expressions (i.e.
(width >= 768px)
).
This package is a spec-compliant media query parser that can be used in Node/Deno/etc, or on the
client that precisely matches the spec right down to the quirks.
These are valid media queries that this library supports:
@media (768px <= width < 1200px);
@media only print and (color);
@media not (not (not (((hover) or ((not (color)))))));
@media (🐈: 😸 /* if cat happy */) {
}
These are invalid media queries that this library will detect:
@media (color) or (hover);
@media (min-width: calc(50vw + 10px));
@media not((color));
@media (768px < = width < 1200px);
Install
This package is available from the npm
registry.
npm install media-query-parser
Usage
Supports JavaScript + TypeScript:
import { parseMediaQuery } from "media-query-parser";
const mediaQuery = parseMediaQuery("screen and (min-width: 768px)");
if (!isParserError(mediaQuery)) {
console.log(mediaQuery);
console.log(stringify(mediaQuery.condition));
}
Can also be imported via require("media-query-parser")
.
Libraries that use this
- (See GitHub for dynamically updated list)
Node versions
This source code of this library supports node >=6.5.0
via require()
and
node >=16.0.0 || ^14.13.1
via import. (Below v6.5.0 is possible but you'd need to transpile the
CommonJS code from ES6 yourself)
Contributing
- PRs welcome and accepted, simply fork and create
- Issues also very welcome
- Treat others with common courtesy and respect 🤝
Dev environment (for contributing) requires:
- node >= 16.14.0
- npm >= 6.8.0
- git >= 2.11
Licence
MIT