npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

media-query-splitting-plugin

v2.0.10

Published

Webpack 4 plugin for styles splitting by media query

Downloads

704

Readme

media-query-splitting-plugin

Webpack 4 plugin for styles splitting by media query. Demo

Npm Version Month Downloads Npm Licence

This plugin is addition to mini-css-extract-plugin. It splits styles from style chunks by media query and creates separate CSS files for mobile, tablet and desktop.

Instalation

npm install --save-dev media-query-splitting-plugin

Chunk before applying

0.04a9302b77ca5a27bfee.css - chunk includes all styles and media queries

Chunk after applying

0.04a9302b77ca5a27bfee.css - common chunk includes the styles without media query conditions 0.desktop.04a9302b77ca5a27bfee.css - styles for desktop media query, by default it's (min-width: 1025px) 0.tabletLandscape.04a9302b77ca5a27bfee.css - (min-width: 769px) and (max-width: 1024px) 0.tabletPortrait.04a9302b77ca5a27bfee.css - (min-width: 569px) and (max-width: 768px) 0.tablet.04a9302b77ca5a27bfee.css - styles for both tabletLandscape and tabletPortrait 0.mobile.04a9302b77ca5a27bfee.css - (max-width: 568px)

Also it handles loading of these files depending of the client's screen width, it happens on loading new chunk or on window resize.

Options

Attention! From version 2.0.0 and above format of options changed. Now it used media query instead of breakpoints

This is default options and can be omitted.

{
  media: {
    mobile: '(max-width: 568px)',
    tabletPortrait: {
      query: '(min-width: 569px) and (max-width: 768px)',
      withCommonStyles: false,
    },
    tabletLandscape: {
      query: '(min-width: 769px) and (max-width: 1024px)',
      withCommonStyles: false,
    },
    desktop: '(min-width: 1025px)',
  },
  minify: true,
}

You can define your own media type in the media option. The plugin will create regular expression to check is media query fit input media query rule.

For example you can create chunk for critical css like that:

{
  media: {
    mobile: '(max-width: 568px)',
    ...
    critical: {
      query: '(min-width: 1px) and (max-width: 568px)',
      exact: true,
      withCommonStyles: false,
    },
  },
}

By default common styles (that doesn't wrapped into media query condition) will be added into media chunk. If you don't want to add common chunk into media chunk, set 'withCommonStyles: false'.

Options can be written in short style as media query string, or in detailed style as object:

Short style:

mobile: '(max-width: 568px)',

Is equal to detailed style:

mobile: {
  query: '(max-width: 568px)',
  exact: false, // include styles that fit condition in 'query' e.g '(max-width: 567px)' or '(min-width: 200px)'
  withCommonStyles: true, // include common styles without media query condition
},

If you want to disable css minification, set minify: false, this parameter by default is true.

Install

npm install --save-dev media-query-splitting-plugin

Usage

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const MediaQuerySplittingPlugin = require('media-query-splitting-plugin')

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[id].[contenthash].css',
    }),
    // MediaQuerySplittingPlugin should be placed under MiniCssExtractPlugin
    new MediaQuerySplittingPlugin({
      // Prevent splitting for some files
      exclude: {
        tailwind: /tailwind-css/,
      },
      // This is default config (optional)
      media: {
        mobile: '(max-width: 568px)',
        tabletPortrait: {
          query: '(min-width: 569px) and (max-width: 768px)',
          withCommonStyles: false,
        },
        tabletLandscape: {
          query: '(min-width: 769px) and (max-width: 1024px)',
          withCommonStyles: false,
        },
        desktop: '(min-width: 1025px)',
      },
      minify: true,
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ]
      }
    ]
  }
}

Server side rendering

The plugin splits each css asset to common chunk (which should be always included to the response) and media chunk (for desktop, tabletPortrait / tabletLandscape / tablet (includes portrait and landscape) or mobile, which should be included depending on client's device).

How to use it with SSR.

All you need is to define client device type (mobile, tablet or desktop) and add style chunk for this device in addition to the common chunk. For example if you use express.js you can define device type depending on req.headers['user-agent'] (use express-device middleware to handle it).

Example:

  const { getBundles } = require('react-loadable/webpack')
  const assets = require('assets.json') // webpack-assets-manifest

  const bundles  = getBundles(loadableAssets, loadableModules).filter(({ file }) => !/map$/.test(file))
  const chunksById = assets[''].css.reduce((result, chunk) => {
    const [ id, mediaType ] = chunk.replace(/.+\//, '').split('.')
    
    if (id) {
      result[id] = result[id] || {}
      result[id][mediaType] = chunk
    }
    
    return result
  }, {})

  const styles   = (
    bundles
      .filter((bundle) => bundle.file.endsWith('.css'))
      .concat({ publicPath: assets.client.css })
      .map(({ publicPath }) => {
        const { isMobile, isTablet } = req

        let mediaType = 'desktop'

        if (isMobile) {
          mediaType = 'mobile'
        }
        else if (isTablet) {
          mediaType = 'tabletPortrait'
        }

        const chunkId = publicPath.replace(/.*\//,'').replace(/\..*/, '')
        const mediaPath = chunksById[chunkId][mediaType]

        if (mediaPath) {
          return `
            <link rel="stylesheet" href="${mediaPath}" />  // Media chunk with common styles (0.${mediaType}.04a9302b77ca5a27bfee.css)
          `
        }
      })
  )