What is @csstools/media-query-list-parser?
@csstools/media-query-list-parser is a utility for parsing CSS media query lists. It allows developers to analyze and manipulate media queries in a structured way, making it easier to work with responsive design rules programmatically.
What are @csstools/media-query-list-parser's main functionalities?
Parsing Media Query Lists
This feature allows you to parse a string of media queries into a structured format. The `parse` function takes a media query list string and returns an object representation of the media queries.
const { parse } = require('@csstools/media-query-list-parser');
const mediaQueryList = 'screen and (min-width: 600px), print';
const parsed = parse(mediaQueryList);
console.log(parsed);
Handling Complex Media Queries
This feature demonstrates the ability to handle more complex media queries with multiple conditions. The parser can break down and structure these complex queries for easier manipulation and analysis.
const { parse } = require('@csstools/media-query-list-parser');
const complexMediaQueryList = 'screen and (min-width: 600px) and (max-width: 1200px), print and (color)';
const parsed = parse(complexMediaQueryList);
console.log(parsed);
Other packages similar to @csstools/media-query-list-parser
postcss-media-query-parser
postcss-media-query-parser is a PostCSS plugin that parses media queries in CSS. It provides similar functionality to @csstools/media-query-list-parser but is designed to work within the PostCSS ecosystem, making it a good choice if you are already using PostCSS for other CSS transformations.
css-mediaquery
css-mediaquery is a utility for parsing and matching CSS media queries. It offers similar parsing capabilities but also includes features for evaluating media queries against a given set of conditions, which can be useful for server-side rendering or testing environments.
Media Query List Parser
Implemented from : https://www.w3.org/TR/mediaqueries-5/
Usage
Add Media Query List Parser to your project:
npm install @csstools/media-query-list-parser @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev
Media Query List Parser depends on our CSS tokenizer and parser algorithms.
It must be used together with @csstools/css-tokenizer
and @csstools/css-parser-algorithms
.
import { parse } from '@csstools/media-query-list-parser';
export function parseCustomMedia() {
const mediaQueryList = parse('screen and (min-width: 300px), (50px < height < 30vw)');
mediaQueryList.forEach((mediaQuery) => {
mediaQuery.walk((entry, index) => {
console.log(index);
console.log(entry.parent.type);
{
if (Array.isArray(entry.node)) {
entry.node.forEach((item) => {
console.log(item.type);
});
}
if ('type' in entry.node) {
console.log(entry.node.type);
}
}
console.log(entry.node.toString());
return false;
});
});
}