npm module to separate media queries from a css string

Usage no npm install needed!

<script type="module">
  import extractCssMedia from 'https://cdn.skypack.dev/extract-css-media';



Provides a function, which parses a given css string and extracts the media query definitions into separate css strings (or ASTs, if configured).

It uses the css module, to parse and compile the input css string.


npm i extract-css-media


The module exports a function which accepts to parameters: the input css string and an options object.


minRules: Number - default: 20

Specifies a minimum number of rules for a media query to be required to split that media query definitions into an extra string.

The background for that is, that there are sometimes media queries which contain only a little amount of definitions. In that case it often makes sense to keep them in the overall css.

compress: Boolean - default: true

The parameter gets passed to css.parse. When set to true, the output css gets minified.

asAst: Boolean - default: false

This option can be used, if the splitted stylesheets should get processed further.

source: String - default: undefined

The source parameter gets passed to css.parse and is used to show the filename, in which a potential parsing errors occurred.

Return: Object

If the execution was successful, the following object gets returned:

    mediaQuery1: CSS-string or AST
    mediaQuery2: CSS-string or AST,
    all: CSS-string or AST of the rules without media queries


const extractMedia = require('extract-css-media')

const extracted = extractMedia(`
    body { 
        color: red 
    @media screen and (min-width: 300px) {
        body {
            color: green
    }`, {
        minRules: 1

console.log(JSON.stringify(extracted, null, 4));


    "screen and (min-width: 300px)": "body{color:green;}",
    "all": "body{color:red;}"


The compress option doesn't produce a fully minimized css. Like you can already see in the example output, the splitting semicolon for css definitions is also added to the last statement of each definition. If you really want to have the smallest css, you should use a real minifier after the media query separation.