Package Exports
- media-query-parser
- media-query-parser/dist/index.js
- media-query-parser/dist/media-query-parser.esm.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (media-query-parser) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
media-query-parser
- Parses correct CSS media queries
- Fails on invalid CSS media queries
- Spec-compliant - https://www.w3.org/TR/mediaqueries-4/
- Zero-dependencies
- TypeScript friendly
- All valid queries parsed, even newer ones like
@media (100px < width < 200px)
Quickfire examples
import { toAST } from 'media-query-parser'
// Simple responsive media query
console.log(toAST('(max-width: 768px)'))
/* [
{
"mediaPrefix":null,
"mediaType":"all",
"mediaCondition":{
"operator":null,
"children":[
{"context":"value",
"prefix":"max",
"feature":"width",
"value":{"type":"<dimension-token>","value":768,"unit":"px","flag":"number"}
}
]
}
}
] */
// Supports comma separated media-query lists
console.log(toAST('print, (not (color))'))
// Trims the `@media` if it starts with it, the `{` and anything that follows
console.log(toAST('@media screen { body { background: #000 } }'))
// Full support for new range syntax
console.log(toAST('(100px < width < 200px)'))
// ...which was no mean feat...
console.log(toAST('(4/3 <= aspect-ratio <= 16/9)'))
// Returns null when it is not valid media query syntax
console.log(toAST('clearly this is not a valid media query')) // => null
// ...even the normal looking but invalid ones:
{
console.log(toAST('(max-width: 768px) and screen')) // => null
// explanation: screen must be on left hand side
console.log(toAST('screen and (max-width: 768px) or (hover)')) // => null
// explanation: spec disallows `and` and `or` on same level as ambiguous
}
Considerations & Caveats
This library does:
- remove extra layers from unnecessary parentheses
(((((max-width: 768px)))))
- parses units, numbers and other values to the spec
- handle unusual whitespace anywhere that the spec allows it
- contain many a unit test
This library does not:
- sanity check the actual media features or their types
(max-power: infinite)
is as valid as(hover: none)
- normalize the media query features (e.g.
(max-width: -100px)
is alwaysfalse
)
Note that:
- Handling individual media features is being developed in a separate project: media-query-fns
Installation
npm install media-query-parser --save
# yarn add media-query-parser
Alternatively, there are also client web builds available:
<!-- window.MediaQueryParser -->
<script src="https://unpkg.com/media-query-parser/dist/media-query-parser.umd.js"></script>
API
License
MIT